Follow up for "Remove Duplicates": What if duplicates are allowed at most twice?
For example, given sorted array A = [1,1,1,2,2,3], your function should return length = 5, and A is now [1,1,2,2,3].
public class Solution { public int removeDuplicates(int[] A) { if (A.length <= 2) return A.length; int prev = 1; // point to previous int curr = 2; // point to current while (curr < A.length) { if (A[curr] == A[prev] && A[curr] == A[prev - 1]) { curr++; } else { prev++; A[prev] = A[curr]; curr++; } } return prev + 1; } } |
public
int
removeDuplicates(
int
[] A) {
if
(A.length ==
0
)
return
0
;
int
p = -
1
;
// pointer to hold the last element of the finished array
for
(
int
i =
0
; i < A.length; i++) {
if
( p-
1
>=
0
&& A[p] == A[i] && A[p-
1
] == A[i])
continue
;
else
p++;
A[p] = A[i];
}
return
p +
1
;
}