LC26.删除有序数组中的重复项

原题链接
image.png

思路:store_index类型双指针

  • 此题看上去是一个升序数组,但是本质上是“相邻重复元素只能保留n个”类型的问题
  • store_index指向开头的位置,遍历指针i指向开头的位置,如果出现符合条件的元素,那么store_index位置填入该元素,同时,store_indexi指针会同时向前走一步。
  • 现在问题聚焦在,怎样判定元素是不是“符合条件”。如果元素和之前的store_index位置(也就是现在的store_index - 1位置)元素是一样的,那么说明元素不符合条件,反之则符合条件。

    代码

    1. class Solution {
    2. public:
    3. int removeDuplicates(vector<int>& nums) {
    4. int store_index = 0;
    5. int n = nums.size();
    6. for (int i = 0; i < n; ++i) {
    7. if (i == 0) {
    8. store_index += 1;
    9. } else {
    10. if (nums[i] != nums[store_index - 1]) {
    11. nums[store_index] = nums[i];
    12. store_index += 1;
    13. }
    14. }
    15. }
    16. return store_index;
    17. }
    18. };