Remove Duplicates from Sorted Array II
Total Accepted: 39950 Total Submissions: 130101My Submissions
Question Solution
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.
Show Tags
问题分析:去掉重复项,这里的重复是指3个以上,去重是指将3个以上项降为2个,还是使用传入的数组作为目标数组存储去重后结果,同时返回去重后的数组内数据个数
public class Solution {
public int removeDuplicates(int[] nums) {
int count=0;
int midc=0;
int size=nums.length;
if(size<=1)
return size;
int i;
for(i=0;i<nums.length-1;i++)
{
if(nums[i]!=nums[i+1])
{
midc++;
if(midc<2)
{
nums[count]=nums[i];
count=count+1;
}
else
{
nums[count]=nums[i];
nums[count+1]=nums[i];
count=count+2;
}
midc=0;
}
else
{
midc++;
}
}
if(midc==0)
{
nums[count]=nums[i];
count++;
}
else
{
nums[count]=nums[i];
nums[count+1]=nums[i];
count=count+2;
}
return count;
}
}