题目:Remove Duplicates from Sorted Array II
难度:medium
问题描述:
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.
解题思路:
给出一个有序数组,将已经重复两次以上的字符剔除,返回剩余数组长度。例如 1,1,1,2,2,3,1,1,1。变化为1,1,2,2,3,1,1。返回7,同时原数组的前7位变为正确的数组。使用一个insert表示即将改写的数组位。遍历整个数组,不用剔除的就填入insert,需要剔除的直接跳过。最后将insert后面的数组位填入与最后一位合法数不同的数。
很简单的一道题,具体代码如下:
public static int removeDuplicates(int[] nums) {
if(nums.length<2){
return nums.length;
}
int temp=nums[0];
int insert=1;
boolean gate=false;
for(int i=1;i<nums.length;i++){
if(nums[i]==temp){
if(gate){
continue;
}else{
gate=true;
nums[insert++]=temp;
}
}else{
gate=false;
nums[insert++]=nums[i];
temp=nums[i];
}
}
if(insert<nums.length){
nums[insert]=nums[insert-1]+1;
}
return insert;
}