原题:
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.
题意:删除数组中的重复数字,要求同一个数字有两次重复,并返回长度
代码和思路:
class Solution {
public int removeDuplicates(int[] nums) {
int i = 0;
for(int n:nums){
//只有在i小于2(小于两个数) 和 后面的数n大于前面第二个数(因为两数重复)时(因为数组是123递增),才进1,否则i指针不动,判断下一个数。
if(i<2 || n > nums[i-2]){
nums[i++] = n;
}
}
return i;
}
}
同理如果是要求只能有一个数重复的,那么就 i<1 || n>[i-1]即可