80. Remove Duplicates from Sorted Array II

problem

solution

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
class Solution {
public:
int removeDuplicates(vector<int>& nums) {
int n= nums.size();
int slow = 0, fast = 1, count =1;
while(fast<n){
if(nums[fast] == nums[slow] && count==1){
count ++;
nums[++slow] = nums[fast];
fast++;
}
else if(nums[fast] == nums[slow] && count==2) fast++;
else if(nums[fast]!=nums[slow]){
nums[++slow] = nums[fast];
count = 1;
fast++;
}

}
return slow+1;

}
};

analysis

  • time complexity O(n)
  • space complexity O(1)