forked from super30admin/Two-Pointers-2
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathremove-duplicates-from-sorted-array-ii.java
More file actions
58 lines (53 loc) · 1.98 KB
/
remove-duplicates-from-sorted-array-ii.java
File metadata and controls
58 lines (53 loc) · 1.98 KB
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
57
58
// Time Complexity : O(2n) = O(n)
// Space Complexity : O(1)
// Did this code successfully run on Leetcode : Yes
// Three line explanation of solution in plain english : We use two pointers, slow and fast. The fast pointer moves forward and counts how many times the same digit appears. When the fast pointer encounters a new element or reaches the end of the array, we check the digit count. We take the minimum of the digit count and 2, and then use the slow pointer to update the array. Once the fast pointer reach the end of array we return the slow index.
class Solution {
public int removeDuplicates(int[] nums) {
int slow =0;
int fast =0;
int count =0;
while(fast< nums.length) {
int curr = nums[fast];
while(fast<nums.length && nums[fast] == curr) {
fast++;
count++;
}
int iter = Math.min(count,2);
while(iter !=0) {
nums[slow] = curr;
slow++;
iter --;
}
count =0;
}
return slow;
}
}
// Another approach which works perfectly with same time and space complexity
// int slow = 0;
// int fast = 0;
// int count =1;
// while(fast < nums.length) {
// if(fast == nums.length-1) {
// int iter = Math.min(count, 2);
// for(int i=0; i<iter; i++) {
// nums[slow] = nums[fast];
// slow++;
// }
// break;
// }
// if(nums[fast] == nums[fast+1]) {
// count+=1;
// } else {
// int iter = Math.min(count, 2);
// for(int i=0; i<iter; i++) {
// nums[slow] = nums[fast];
// slow++;
// }
// count =1;
// }
// fast++;
// }
// return slow;
// }