C++ code, no trick

  • 8

    Use an index last to record the next written position (i.e. copy a new element to last+1).

    class Solution {
        int removeDuplicates(vector<int>& nums) {
            int last=0, i, len=nums.size();
            if(!len) return 0;
            for(i=0; i<len;++i)
                if(nums[i]!=nums[last]) nums[++last] = nums[i];
            return last+1;

Log in to reply

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.