每日一题:leetcode 80
倒序遍历,减少移动次数
利用count计数,重复数字到底有多少,如果count>=2,说明超过了2个重复数字,那么保留前两个,将后面的重复数字删除
删除的方法:将后面的数字前移
public int removeDuplicates(int[] nums) {
if(nums.length==0){
return 0;
}
int res=nums.length;
int count=0;
for(int i=res-2;i>=0;i--){
if(nums[i]==nums[i+1]){
count++;
}else if(nums[i]!=nums[i+1]&&count>=2){
//需要删除重复的,并将后面的移动过来
for(int h=i+count+2;h<res;h++){
nums[h-count+1]=nums[h];
}
res-=(count-1);
count=0;
}else{
count=0;
}
}
if(count>=2){
//需要删除重复的,并将后面的移动过来
for(int h=count+1;h<res;h++){
nums[h-count+1]=nums[h];
}
res-=(count-1);
}
return res;
}