记录十一——删除已排序数组的重复项

删除已排序数组中的重复项

给定一个已排序的数组号,删除重复项,使每个元素只出现一次,并返回新的长度。
不要为另一个数组分配额外的空间,您必须使用O(1)额外内存修改输入数组。


Given nums = [1,1,2],
Your function should return length = 2, with the first two elements of nums being 1 and 2 respectively.
It doesn’t matter what you leave beyond the returned length.


Given nums = [0,0,1,1,1,2,2,3,3,4],
Your function should return length = 5, with the first five elements of nums being modified to 0, 1, 2, 3, and 4 respectively.
It doesn’t matter what values are set beyond the returned length.


【注】:虽然返回的是数组长度,但是数组需要变化
思路:看了一下解析,发现自己把这道题想的复杂了。要移除数组中重复的元素,何必要将重复的元素往后移呢,这样只会无用的增加时间复杂度。只需遍历一遍数组,将数组中前面重复的元素用后面不重复的元素替换掉即可。

class Solution {
    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;
    }
}

时间复杂度:O(n),空间复杂度:O(1)

猜你喜欢

转载自blog.csdn.net/w1375834506/article/details/88594304