Remove duplicates from sorted array II
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 int removeDuplicates(int[] nums) {
if (nums == null || nums.length == 0) {
return 0;
}
int size = 0;
int count = 0;
for (int i = 1; i < nums.length; i++) {
if (nums[i] == nums[size]) {
count++;
} else {
count = 0;
}
if (count < 2) {
nums[++size] = nums[i];
}
}
return size + 1;
}
思路:
使用count来计数,出现1次(count = 0),2次(count = 1)的加入数组,出现3次(count = 2)及以上的跳过。
计数值在出现新数字时清零。