- Remove Duplicates from Sorted Array II
Given a sorted array, remove the duplicates in place such that each element appear at most twice and return the new length.
If a number appears more than two times, then keep the number appears twice in array after remove.
Example
Example 1:
Input: []
Output: 0
Example 2:
Input: [1,1,1,2,2,3]
Output: 5
Explanation:
the length is 5: [1,1,2,2,3]
Notice
Need to operate in the original array
解法1:
class Solution {
public:
/**
* @param A: a list of integers
* @return : return an integer
*/
int removeDuplicates(vector<int> &nums) {
int n = nums.size();
if (n <= 2) return n;
unordered_map<int, int> um;
int pos = 0;
int len = n;
for (int i = 0; i < n; ++i) {
um[nums[i]]++;
if (um[nums[i]] <= 2) {
nums[pos] = nums[i];
pos++;
}
else {
len--;
}
}
return len;
}
};