Remove Duplicates from Sorted Array II in C++


Suppose we have a sorted array nums, we have to remove the duplicates in-place such that duplicates elements will appear at most twice and return the new length. To do this task we cannot take extra space. We have to solve this with O(1) amount of space. For example, if the array is like [0,0,0,1,1,1,1,2,3,3], then the output will be [0,0,1,1,2,3,3], its length is 7

Let us see the steps −

  • len := 2 and n := size of array

  • if n <= 2, then return n

  • for i := 2 to n

    • if nums[i] != nums[len - 2] or nums[i] != nums[len - 1]

      • nums[len] := nums[i], and increase len by 1

  • return len

Example

Let us see the following implementation to get better understanding −

class Solution {
   public:
   int removeDuplicates(vector& nums) {
      int len = 2;
      int n = nums.size();
      if(n <= 2)return n;
      for(int i = 2; i < n; i++){
      if( nums[i] != nums[len - 2] || nums[i] != nums[len - 1]){
            //cout << len << " " << " " << i << " "<< nums[i] << endl;
            nums[len] = nums[i];
            len++;
         }
      }
      return len;
   }
};

Input

[0,0,0,1,1,1,1,2,3,3]

Output

[0,0,1,1,2,3,3]

raja
Published on 03-Feb-2020 10:13:04
Advertisements