LC26.删除有序数组中的重复项
思路:store_index类型双指针
- 此题看上去是一个升序数组,但是本质上是“相邻重复元素只能保留n个”类型的问题
store_index
指向开头的位置,遍历指针i
指向开头的位置,如果出现符合条件的元素,那么store_index
位置填入该元素,同时,store_index
和i
指针会同时向前走一步。现在问题聚焦在,怎样判定元素是不是“符合条件”。如果元素和之前的
store_index
位置(也就是现在的store_index - 1
位置)元素是一样的,那么说明元素不符合条件,反之则符合条件。代码
class Solution {
public:
int removeDuplicates(vector<int>& nums) {
int store_index = 0;
int n = nums.size();
for (int i = 0; i < n; ++i) {
if (i == 0) {
store_index += 1;
} else {
if (nums[i] != nums[store_index - 1]) {
nums[store_index] = nums[i];
store_index += 1;
}
}
}
return store_index;
}
};