simple c++ solution with O(n) time and O(1) space using while loop

  • 0
    int len = (int)nums.size();
            if (len <= 1){return len;}
            int cur = 0, head = 1;
            while (head < len){
                if (nums[head] == nums[cur]) {++head;}
                else{ nums[++cur] = nums[head++];}
            return cur+1;

    the idea is to let cur point to the last non-duplicate number, if the element head points does not equal to nums[cur],
    then assign this element to position after cur, then increase head by one.

Log in to reply

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