26. Remove Duplicates from Sorted Array*(快慢指针)

description:

Given a sorted array nums, 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.
Note:

Example:

Example 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.
Example 2:

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.

my answer:

感恩

快慢指针,慢的指向的一直都是新的,也就是说来一个新的它才往前走一步,快的就是不断向前,发现和慢的不一样的就汇报给那个慢的,然后慢的更新。如果二者相等,则慢的不动,快的前进一步;如果二者不等,则慢的前进一步的同时更新那个新一步指向的数字为现在快指针指向的新数字,快的同时也往前走一步。

大佬的answer:

class Solution {
public:
    int removeDuplicates(vector<int>& nums) {
        if(nums.empty()) return 0;
        int n = nums.size();
        int pre = 0, cur = 0;
        while(cur<n){
            if(nums[pre] == nums[cur]){
                cur++;
            }else{
                nums[++pre] = nums[cur++];
            }
        }return pre+1;
    }
};

relative point get√:

hint :

猜你喜欢

转载自www.cnblogs.com/forPrometheus-jun/p/10889152.html