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.
discuass的讲解:
https://discuss.leetcode.com/topic/7673/share-my-o-n-time-and-o-1-solution-when-duplicates-are-allowed-at-most-k-timeshttps://discuss.leetcode.com/topic/17180/3-6-easy-lines-c-java-python-ruby
提示上采用双指针。
class Solution {
int remove(vector
& nums, int k)
{
int n=nums.size();
int i=1,j=1,cnt=1;
//i指向原来的数组,j指向新的数组
while(i
& nums) {
if(nums.size()==0)
return 0;
return remove(nums,2);
}
};
int removeDuplicates(vector
& nums) {
int i = 0;
for (int n : nums)
if (i < 2 || n > nums[i-2])
nums[i++] = n;
return i;
}