Saturday, June 25, 2016

80. Remove Duplicates from Sorted Array II

Maintain two pointers. One is to scan every elements from position 2 and the other keeps the end position for the valid array.

1:  class Solution {  
2:  public:  
3:    int removeDuplicates(vector<int>& nums) {  
4:      if (nums.size() < 3) return nums.size();  
5:      int end = 2;  
6:      for (int i = 2; i < nums.size(); i++) {  
7:        if (nums[i] != nums[end-1] || nums[i] != nums[end-2]) {  
8:          swap(nums[i], nums[end]);  
9:          end++;  
10:        }  
11:      }  
12:      return end;  
13:    }  
14:  };  

When I revisited this problem, I had a bit more concise way.

1:  class Solution {  
2:  public:  
3:    int removeDuplicates(vector<int>& nums) {  
4:      if (nums.size() < 3) return nums.size();  
5:      int i, j;  
6:      for (i = 2, j = 2; j < nums.size(); i++, j++) {  
7:        if (nums[i-2] != nums[j]) swap(nums[i], nums[j]);  
8:        else i--;   
9:      }  
10:      return i;  
11:    }  
12:  };  

No comments:

Post a Comment