26. 删除有序数组中的重复项(左右双指针)

 

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 by modifying the input array in-place with O(1) extra memory.

Example:

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 new length.

 

我们让慢指针 slow 走在后面,快指针 fast 走在前面探路,找到一个不重复的元素就赋值给 slow 并让 slow 前进一步。

这样,就保证了 nums[0..slow] 都是无重复的元素,当 fast 指针遍历完整个数组 nums 后,nums[0..slow] 就是整个数组去重之后的结果。

 

 

class Solution:
    def removeDuplicates(self, nums: List[int]) -> int:
        l = 0
        r = 0
        n = len(nums)
        while r < n:
            #由于是保留 k 个相同数字,对于前 k 个数字,我们可以直接保留
            #对于后面的任意数字,能够保留的前提是:与当前写入的位置前面的第 k 个元素进行比较,不相同则保留
            if l < 1 or nums[l-1] != nums[r]:
                nums[l] = nums[r]
                l+=1
            r+=1
        return l
       

 

 

 

class Solution {
public:

    int removeDuplicates(vector<int>& nums) {
        int slow = 0;
        for(int i = 0;i < nums.size();i++) {
            if (nums[slow]!=nums[i]) {
                nums[++slow] = nums[i];
            }
        }
        return slow+1;
    }
};

 

 

class Solution {
public:

    int removeDuplicates(vector<int>& nums) {
        int i = 0;
        int j = 0;
        while(j< nums.size()) {
            if (nums[i]!=nums[j]) nums[++i] = nums[j];
            j++;
        }
        return i+1;
    }
};

 

posted @ 2018-03-25 11:29  乐乐章  阅读(158)  评论(0编辑  收藏  举报