Easy to understand, allow upto K duplicate solution - C++ - 16ms


  • 0
    P

    Sharing my solution to this problem:

        static const int MAX_DUP = 1;    /* Change this constant to control #duplicates */
        int removeDuplicates(vector<int>& nums) {
            if(nums.size() < 2) return nums.size();
            int old = 1, dup_cnt = MAX_DUP;
            for(int i = old; i < nums.size(); ++i) {
                /* Include this number if it is new and reset the duplicate count       */
                if(nums[i] != nums[i - 1]) { nums[old++] = nums[i]; dup_cnt = MAX_DUP;  }
                /* If duplicate count is non-zero and this is duplicate, include number */
                else if(dup_cnt)           { nums[old++] = nums[i]; dup_cnt--;          }
            }
            nums.resize(old);
            return nums.size();
        }

Log in to reply
 

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