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.
代码;用一个额外的数组,记录下重复次数不超过2次的部分,然后再赋值给nums
代码如下(已通过leetcode)
public class Solution {
public int removeDuplicates(int[] nums) {
if(nums.length==0) return 0;
boolean[] flag=new boolean[nums.length];
int count=1;
int sum=1;
for(int i=1;i<nums.length;i++) {
if(nums[i]==nums[i-1]) {
count++;
if(count<3) sum++;
else flag[i]=true;
} else {
count=1;
sum++;
}
}
int[] temp=new int[sum];
int j=0,i=0;
while(i<nums.length&&j<sum) {
if(!flag[i]) {
temp[j]=nums[i];
i++;
j++;
} else i++;
}
for(int k=0;k<sum;k++)
nums[k]=temp[k];
return sum;
}
}