Skip to content

Commit 31641be

Browse files
committed
add solution of problem 80: remove duplicates from sorted array
1 parent 86489f4 commit 31641be

2 files changed

Lines changed: 38 additions & 0 deletions

File tree

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,7 @@
1+
Follow up for "Remove Duplicates":
2+
What if duplicates are allowed at most *twice*?
3+
4+
For example,
5+
Given sorted array *nums* = `[1,1,1,2,2,3]`,
6+
7+
Your function should return length = `5`, with the first five elements of nums being `1`, `1`, `2`, `2` and `3`. It doesn't matter what you leave beyond the new length.
Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
public class Solution {
2+
public int removeDuplicates(int[] nums) {
3+
if (nums == null || nums.length == 0)
4+
return 0;
5+
6+
int slowIdx = 0;
7+
int fastIdx = 0;
8+
int cnt = 0;
9+
10+
int idx = 0;
11+
while (fastIdx < nums.length) {
12+
while (fastIdx < nums.length && nums[slowIdx] == nums[fastIdx]) {
13+
fastIdx++;
14+
}
15+
16+
if (slowIdx != fastIdx - 1) {
17+
nums[idx++] = nums[slowIdx];
18+
nums[idx++] = nums[fastIdx - 1];
19+
cnt += 2;
20+
21+
slowIdx = fastIdx;
22+
} else {
23+
nums[idx++] = nums[slowIdx];
24+
slowIdx = fastIdx;
25+
cnt++;
26+
}
27+
}
28+
29+
return cnt;
30+
}
31+
}

0 commit comments

Comments
 (0)