leetcode [27] 移除元素 / Remove Element

在这里插入图片描述

题目地址

https://leetcode-cn.com/problems/remove-element/

思路

这道题目也是O(n)的解法
建议昨晚这道题,接着再去做 26. 删除排序数组中的重复项, 对这种类型的题目就有有所感觉

解法

class Solution {
public:
    int removeElement(vector<int>& nums, int val) {
        int index = 0;
        for (int i = 0; i < nums.size(); i++) {
            if (val != nums[i]) {
                nums[index++] = nums[i]; // 注意是index++ 而不是 ++index
            }
        }
        return index;
    }
};

我是代码君,在BAT从事技术研发多年,利用工作之余重刷leetcode,更多原创文章欢迎关注「代码随想录」。

发布了236 篇原创文章 · 获赞 251 · 访问量 27万+

猜你喜欢

转载自blog.csdn.net/youngyangyang04/article/details/105355176