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 {
/**
* @param A: a array of integers
* @return : return an integer
*/
public int removeDuplicates(int[] nums) {
if(nums.length == 0) return 0;
int index = 0;
boolean twice = false;
for(int i = 1; i < nums.length; i++) {
if(nums[index] != nums[i] || !twice) {
if(nums[index] == nums[i]) {
twice = true;
}
else {
twice = false;
}
nums[index + 1] = nums[i];
index++;
}
}
return index + 1;
}
}