Skip to content

Commit 77139e7

Browse files
committed
Remove Duplicates from Sorted Array II
1 parent 4451f61 commit 77139e7

File tree

1 file changed

+37
-0
lines changed

1 file changed

+37
-0
lines changed
Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
/**
2+
* Follow up for "Remove Duplicates": What if duplicates are allowed at most twice?
3+
*
4+
* For example,
5+
*
6+
* Given sorted array A = [1,1,1,2,2,3],
7+
*
8+
* Your function should return length = 5, and A is now [1,1,2,2,3].
9+
*
10+
*/
11+
public class RemoveDuplicatesFromSortedArrayII {
12+
public int removeDuplicates(int[] A) {
13+
int length = A.length;
14+
if (length < 3)
15+
return length;
16+
int slow = 0, fast = 1, idx = 0;
17+
while (fast < length) {
18+
while (fast < length && A[fast] == A[slow]) {
19+
fast++;
20+
}
21+
if (fast - slow <= 2) {
22+
while (slow < fast) {
23+
A[idx++] = A[slow++];
24+
}
25+
} else {
26+
A[idx++] = A[slow++];
27+
A[idx++] = A[slow++];
28+
slow = fast;
29+
}
30+
fast++;
31+
}
32+
while (slow < length) {
33+
A[idx++] = A[slow++];
34+
}
35+
return idx;
36+
}
37+
}

0 commit comments

Comments
 (0)