【原题】 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. 【解释】 作为删除数组中重复元素的进化版,要求最后目标数组中最多只能有每个元素最多重复两次。 【思路】 在Remove Duplicates from Sorted Array一题中,我们只需要记录目标数组下一个该插入的位置,让后续符合要求的元素插入该位置即可。利用同样的思想,只是在比较的时候不是和前一个元素比较,而是前两个元素。
public int removeDuplicates(int[] nums) {
int pos=0;//记录下一个插入的位置
for(int i=0;i<nums.length;i++){
if(i<2||nums[i]>nums[pos-2])//和前两个元素比较
nums[pos++]=nums[i];
}
return pos;//犹豫pos从零开始,所以最后即为目标数组的长度
}