describe:
Follow up for ”Remove Duplicates”: What if duplicates are allowed at most twice?
For example, Given sorted array A = [1,1,1,2,2,3],
Your function should return length = 5, and A is now [1,1,2,2,3]
Analysis:
Add a variable to record the number of times the element appears. This problem can be solved with a single variable because the array has been sorted. If it is an unsorted array, you need to introduce a hashmap to record the number of occurrences.
Code 1:
// LeetCode, Remove Duplicates from Sorted Array II
// 时间复杂度 O(n),空间复杂度 O(1)
// @author hex108 (https://github.com/hex108)
class Solution {
public:
int removeDuplicates(vector<int>& nums) {
if (nums.size() <= 2) return nums.size();
int index = 2;
for (int i = 2; i < nums.size(); i++){
if (nums[i] != nums[index - 2])
nums[index++] = nums[i];
}
return index;
}
};
Code 2:
class Solution {
public:
int removeDuplicates(vector<int>& nums) {
const int n = nums.size();
int index = 0;
for (int i = 0; i < n; ++i) {
if (i > 0 && i < n - 1 && nums[i] == nums[i - 1] && nums[i] == nums[i + 1])
continue;//结束这次循环进入下一次的循环;
nums[index++] = nums[i];
}
return index;
}
};