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.
===================================================================
題目鏈接:https://leetcode.com/problems/remove-duplicates-from-sorted-array-ii/
題目大意:要求排序數組中每個數值最多出現兩次,並返回新數組長度。
思路:記錄每個數值個數,最多保留兩個,邊訪問邊記錄。
參考代碼:
class Solution {
public:
int removeDuplicates(vector<int>& nums) {
int n = nums.size() , ans = 0 ;
if ( n == 0 )
return 0 ;
for ( int i = 0 ; i < n ; i ++ )
{
int cur = nums[i] , sum = 1 ;
while ( i + 1 < n && nums[i+1] == cur )
{
i ++ ;
sum ++ ;
}
sum = sum > 2 ? 2 : sum ;
for ( int j = ans ; j < ans + sum ; j ++ )
nums[j] = cur ;
ans += sum ;
}
return ans ;
}
};