题目:
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.
大概意思:有一个有序的数组nums, 经过处理之后数组中最多不会有三个重复的元素。返回值是新数组的长度。
思路
1.设置两个指针i,end. i指向的是数组的头。end指向数组的尾巴。
2.看看nums[i+2]是不是等于i,如果是的话(明显这个元素的个数大于两个)删除并且end–。如果不是i继续往前走。
3.返回是end+1
如图所示:
太简单,不用画图。
代码如下
public int removeDuplicates(int[] nums) {
if(nums.length==0)
return 0;
int i=0;
int end=nums.length-1;
while ((i+2)<=end){ //注意这个越界问题
if(nums[i]==nums[i+2]){
removeEle(nums,i+2);//把i+2给删除掉
end--;//维护一下数组的长度
}else {
i++;//如果这个元素个数不大于3
}
}
return end+1;
}
public void removeEle(int []nums,int index){
for(int i=index;i<nums.length-1;i++){
nums[i]=nums[i+1];
}
}
分析:这里使用了数组删除的操作比较费时间,不过整理来看思路比较简单。leetcode测试时间还是很快的。