原地移除元素--c++版

发布时间 2023-11-24 16:26:07作者: 一名博客

代码

class Solution {
public:
    int removeElement(vector<int>& nums, int val) {
        //暴力法
        // int numSize = nums.size();
        // int ptr = 0;
        // int count = numSize;
        // int tail = numSize - 1;//如果最后是val,val就变多了,设置一个尾巴是为防止val变多
        // //1. 找尾巴
        // while (tail >= 0 && nums[tail] == val) {
        //     tail--;
        //     count--;
        // } 
        // //cout << tail;
        // //特俗情况
        // if (tail == -1) {
        //     nums.clear();
        //     std::vector<int>().swap(nums);
        // }
        // //2. 从前往后找,找到一个val,就覆盖,没找到就ptr+1,这里是if else关系,不是每次都要ptr+1
        // while (ptr < tail) {
        //     //1. 找到val
        //     if (val == nums[ptr]) {
        //         //2. 覆盖
        //         int prev = ptr;
        //         int next = ptr + 1;
        //         while (next <= tail) {//<=是为了把最后一个元素也参与覆盖
        //             nums[prev] = nums[next];
        //             prev++;
        //             next++;
        //         }
        //         count--;
        //     }
        //     else ptr++;
        // }
        // return count;


        //双指针,思路:fast指针指向需要给新数组的元素,slow指针指向新数组的下标
        int fast = 0;
        int slow = 0;
        int numSize = nums.size();

        while (fast < numSize) {
            if (nums[fast] == val) fast++;
            else nums[slow++] = nums[fast++];
        }

        return slow;
    }
};