080.Remove Duplicates from Sorted Array II

Solution 1: accepted 1ms

In case we need to allow k duplicates, we only change the maximum of show to k.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
public int removeDuplicates(int[] nums) {
if (nums.length == 0)
return 0;
int show = 1;
int count = 1;
for (int i = 1; i < nums.length; i++) {
if (nums[i] == nums[i - 1]) {
if (show == 2) { // change to k
continue;
} else {
nums[count] = nums[i];
show++;
count++;
}
} else {
nums[count] = nums[i];
show = 1;
count++;
}
}
return count;
}