-
Notifications
You must be signed in to change notification settings - Fork 11
/
80. Remove Duplicates from Sorted Array II.cpp
56 lines (49 loc) · 1.73 KB
/
80. Remove Duplicates from Sorted Array II.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
//Runtime: 12 ms, faster than 46.22% of C++ online submissions for Remove Duplicates from Sorted Array II.
//Memory Usage: 11.3 MB, less than 13.64% of C++ online submissions for Remove Duplicates from Sorted Array II.
class Solution {
public:
int removeDuplicates(vector<int>& nums) {
int n = nums.size();
int slow = 0, fast = 0;
bool first;
while(fast < n){
// cout << slow << " <- " << fast << endl;
nums[slow] = nums[fast];
if(slow == 0 || nums[slow] != nums[slow-1]){
first = true;
}else{
first = false;
}
if(first){
++fast;
}else{
while(fast < n && nums[fast] == nums[slow]){
++fast;
}
}
++slow;
}
return slow;
}
};
//https://leetcode.com/problems/remove-duplicates-from-sorted-array-ii/discuss/27976/3-6-easy-lines-C%2B%2B-Java-Python-Ruby
//Runtime: 4 ms, faster than 99.33% of C++ online submissions for Remove Duplicates from Sorted Array II.
//Memory Usage: 11.3 MB, less than 14.37% of C++ online submissions for Remove Duplicates from Sorted Array II.
class Solution {
public:
int removeDuplicates(vector<int>& nums) {
int n = nums.size();
int slow = 0;
int k = 2;
for(int fast = 0; fast < n; ++fast){
if(slow < k || nums[fast] != nums[slow-k]){
/*
only update nums[slow] when
there are < k nums[fast] in the new array
*/
nums[slow++] = nums[fast];
}
}
return slow;
}
};