Remove Duplicates from Sorted Array II
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.
解题思路:
这道题跟之前那道删除重复数的思路是一样的,无非就是判断当前数与后面第二个数是否一样。
public class Solution {
public int removeDuplicates(int[] nums) {
int length = nums.length;
int len1 = 0;
int len2 = 0;
while(len1<length)
{
if(len1+2>=length || nums[len1] != nums[len1+2])
nums[len2++] = nums[len1++];
else
{
int len = len1+3;
while(len<length && nums[len1] == nums[len])
len++;
nums[len2++] = nums[len1++];
nums[len2++] = nums[len1++];
len1 = len;
}
}
return len2;
}
}