Concise C++ solution


  • 0
        int removeDuplicates(vector<int>& nums) {
            int i = 0, streak = 0;
            for( int j=1; j<nums.size(); j++ ) {
                streak = nums[j] == nums[j-1] ? streak + 1 : 0;
                if( streak <= 1 ) nums[++i] = nums[j];
            }
            return nums.empty() ? 0 : i+1;
        }
    

    And also can be extended to solve K duplicates case, just a little bit modification.

        int removeDuplicates(vector<int>& nums, int k ) {
            int i = 0, streak = 0;
            for( int j=1; j<nums.size(); j++ ) {
                streak = nums[j] == nums[j-1] ? streak + 1 : 0;
                if( streak <= k-1 ) nums[++i] = nums[j];
            }
            return nums.empty() ? 0 : i+1;            
        }

  • 0

    @Tiejun Smart trick. Since the program only checks top i+1 elements, It saves the time from erasing the duplicated.


Log in to reply
 

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