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.
本题需要注意的一点是,当修改了数组的i-2个值之后,有可能当前值和第i-2是同一个值,看了答案才把这个问题解决,思路是,比较的是更改数组的第i-2个值,而不是进度-2的值,代码如下:
1 public class Solution { 2 public int removeDuplicates(int[] nums) { 3 int index=0; 4 for(int i=0;i<nums.length;i++){ 5 if(index<2||nums[index-2]!=nums[i]){ 6 nums[index++] = nums[i]; 7 } 8 } 9 return index; 10 } 11 }