LC80.删除有序数组中的重复项II
思路:
- 标准的
store_index
类型模板题。本质上是`数组中相邻重复元素允许保留n个
问题。 - 相当于加强版的
unique
函数。 - 起始的
store_index
指向数组的开头位置,遍历指针i
也指向数组的开头位置,如果当前位置的数字符合条件,那么就将其放入store_index
位置当中,同时store_index += 1
如何判定“当前位置的数字符合条件”?如果
nums[i] == nums[store_index - 1] == nums[store_index - 2]
,那么就不符合条件,反之则符合条件。代码
class Solution {
public:
int removeDuplicates(vector<int>& nums) {
int store_index = 0, n = nums.size();
for (int i = 0; i < n; ++i) {
if (i <= 1) {
store_index += 1;
} else {
if (nums[i] != nums[store_index - 1] || nums[i] != nums[store_index - 2]) {
nums[store_index] = nums[i];
store_index += 1;
}
}
}
return store_index;
}
};