Categories
不学无术

LeetCode 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.
For example,
Given input array 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.

思路

倆指针~一个指向当前实际有效的位置,一个指向当前处理的位置
题外话:经历感冒鼻塞喉咙痛快一周,脑子终于是清楚了!

代码

class Solution {
public:
    int removeDuplicates(vector<int>& nums) {
        int numSz = nums.size();
        if(numSz <= 1)
            return numSz;
        int i=0;
        int j=1;
        while(j < numSz){
            if(nums[j] == nums[i])
                j++;
            else {
                nums[++i] = nums[j];
                j++;
            }
        }
        return i+1;
    }
};