Question
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.
本题难度Medium。
【题意】
要对nums
进行修改,把出现2次以内的重复数放到前面。然后返回长度。
【复杂度】
时间 O(N) 空间 O(1)
【思路】
与Remove Duplicates from Sorted Array思路一样,也是用快慢指针。两者共同本质就是:
什么情况下慢指针(left)移动(同时移动元素)
I:
if(nums[i-1]!=nums[i]) nums[left++]=nums[i]
II:
if(nums[i-1]!=nums[i]||count<=2) nums[left++]=nums[i]
【代码】
public class Solution {
public int removeDuplicates(int[] nums) {
//require
int size=nums.length;
if(size<1)
return 0;
int ans=1,count=1,left=1;
//invariant
for(int i=1;i<size;i++){
if(nums[i-1]==nums[i]){
count++;
if(count<=2){
nums[left++]=nums[i];
ans++;
}
}else{
count=1;
ans++;
nums[left++]=nums[i];
}
}
//ensure
return ans;
}
}