双指针应用一:数组移除元素

2021-05-07  本文已影响0人  程一刀

题目地址:https://leetcode-cn.com/problems/remove-element/

题目描述:给你一个数组 nums 和一个值 val,你需要 原地 移除所有数值等于 val 的元素,并返回移除后数组的新长度。不要使用额外的数组空间,你必须仅使用 O(1) 额外空间并 原地 修改输入数组。元素的顺序可以改变。你不需要考虑数组中超出新长度后面的元素。

代码参考:

#include <iostream>
#include <vector>
using  namespace::std;
class Solution {
public:
    int removeElement(vector<int>& nums, int val) {
        int slowIndex = 0;
        for (int fastIndex = 0; fastIndex < nums.size(); fastIndex ++) {
            if (nums[fastIndex] != val) {
                nums[slowIndex++] = nums[fastIndex];
            }
        }
        return  slowIndex;
    }
};

int main(int argc, const char * argv[]) {
    // insert code here...
    vector<int> numberAry = {1,2,3,4,5};
    int lenth = Solution().removeElement(numberAry, 3);
    return 0;
}

参考地址:https://github.com/youngyangyang04/leetcode-master/blob/master/problems/0027.%E7%A7%BB%E9%99%A4%E5%85%83%E7%B4%A0.md

上一篇 下一篇

猜你喜欢

热点阅读