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一样,只能在当前数组中操作。同等题目,如果改成保留n个相同的元素,做法一样。。
只要当前元素比倒数第二个新存入元素大,则可以存入。这样就保证了最多两个相同。
直接看代码解析
class Solution { public int removeDuplicates(int[] nums) { if(nums==null) return 0; if(nums.length<=2) return nums.length; int count=1;//用一个新指针,表示新存元素。 for(int i=1;i<nums.length;i++){
//保存两个相同的,所以前两个直接可以存进去。当存进数组以后,数组中元素会发生变化。所以当前元素只要比倒数第二个新存入的元素大,就可以直接存入,相等的就忽略。因为,
//相等,表明最后两个新村元素相等,这时这个元素又相等,就不能存入了。
if(i<2||nums[i]>nums[count-2]) nums[count++]=nums[i]; } return count; } }
当然,这题也可以使用另外一个变量来表示相等元素的个数,当前元素和前一个元素相等时,而且此变量小于2,则添加到前;当比前面大时,也添加,同时更新该变量为初始值1