Follow up for “Remove Duplicates”:
What if duplicates are allowed at most twice?

For example,
Given sorted array nums = [1,1,1,2,2,3],

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.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
public class Solution {
public int removeDuplicates(int[] nums) {
if (nums == null){return 0;}
int index = 0;

for (int num : nums){
if (index < 2 || num > nums[index - 2]){
nums[index++] = num;
}
}

return index;
}
}

Extension to all duplicates at most K times

From Leetcode post

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
int removeDuplicates(int A[], int n, int k) {
if (n <= k) return n;
int i = 1, j = 1;
int cnt = 1;

while (j < n) {
if (A[j] != A[j-1]) {
cnt = 1;
A[i++] = A[j];
}
else {
if (cnt < k) {
A[i++] = A[j];
cnt++;
}
}
++j;
}
return i;
}