C++ 32ms Simple Solution: O(1)space O(n)time

  • 1
    class Solution {
        int removeDuplicates(vector<int>& nums) {
            if(nums.size() < 2) return nums.size();
            int p=1; // index of current unique number
            for(int i=1; i<nums.size(); ++i) {
                if(nums[i] != nums[i-1]) {
                    nums[p++] = nums[i]; //place the next unique number at p
            return p;

    Here i is the index of the entire array, while p is the index of the result array, that contains unique numbers. When i-th is unique, p-th will copy i-th value and p will move forward. Otherwise, p will stay until i finds the next unque one.

Log in to reply

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