[LeetCode]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.
解题思路:
该题目类似于这个题目, 也是用两个指针,但需要记录变量出现的次数。代码如下:
class Solution {
public:
int removeDuplicates(vector<int>& nums) {
size_t n = nums.size();
if (n <= 2) return n;
size_t i = 2;
for (size_t j = 2; j < n; ++j) {
if (nums[j] != nums[i - 2]) {
nums[i++] = nums[j];
}
}
return i;
}
};

浙公网安备 33010602011771号