26.Remove Duplicates from Sorted Array

题目

Given a sorted array, remove the duplicates in place such that each element appear only once and return the new length.
Do not allocate extra space for another array, you must do this in place with constant memory.
给定一个已经排好序的数组,算出其中不重复的元素的个数,假设个数为n,则保证数组的前n个元素为不重复的这n个元素,不用管剩下的位置

#解法一
首先判断数组为空、只有一个元素的情况。这时不需要对数组进行操作,直接返回数组长度就可以。
对数组进行遍历,因为数组已经排序,所以直接判断前后两个元素是否相等就知道这个元素是否是第一次出现。然后将数组第n位替换掉即可

    public int removeDuplicates(int[] nums) {
        if(nums.length <= 1){
            return nums.length;
        }
        int res = 1;
        for(int i=1;i<nums.length;i++){
            if(nums[i] != nums[i-1]){
                 nums[res++] = nums[i];
            }
        }
        return res;
    }

解法二

还是先判断特殊条件,当数组为空的时候返回0;
然后从数组的第二个元素开始遍历,判断当前元素是否在之前曾经出现过,如果是第n个不重复元素,覆盖数组中的第n个位置,继续遍历

public int removeDuplicates(int[] nums) {
    if (nums.length == 0)return 0;
    int i = 0;
    for (int j = 1; j < nums.length; j++) {
        if (nums[j] != nums[i]) {
            i++;
            nums[i] = nums[j];
        }
    }
    return i + 1;
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容