leetcode-master/problems/0027.移除元素.md

1.8 KiB
Raw Blame History

笔者在BAT从事技术研发多年利用工作之余重刷leetcode更多原创文章请关注公众号「代码随想录」。

题目地址

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

建议做完这道题,接着再去做 26. 删除排序数组中的重复项, 对这种类型的题目就有有所感觉

暴力解法

时间复杂度O(n^2) 空间复杂度O(1)

class Solution {
public:
    int removeElement(vector<int>& nums, int val) {
        int size = nums.size();
        for (int i = 0; i < size; i++) {
            if (nums[i] == val) { // 发现需要移除的元素,就将数组集体向前移动一位
                for (int j = i + 1; j < size; j++) {
                    nums[j - 1] = nums[j];
                }
                i--; // 因为下表i以后的数值都向前移动了一位所以i也向前移动一位
                size--;// 此时数组的大小-1
            }
        }
        return size;

    }
};

快慢指针解法

时间复杂度O(n) 空间复杂度O(1)

class Solution {
public:
    int removeElement(vector<int>& nums, int val) {
        int slowIndex = 0; // index为 慢指针
        for (int fastIndex = 0; fastIndex < nums.size(); fastIndex++) {  // i 为快指针
            if (val != nums[fastIndex]) { //将快指针对应的数值赋值给慢指针对应的数值
                nums[slowIndex++] = nums[fastIndex]; 注意这里是slowIndex++ 而不是slowIndex--
            }
        }
        return slowIndex;
    }
};

笔者在先后在腾讯和百度从事技术研发多年利用工作之余重刷leetcode本文 GitHubhttps://github.com/youngyangyang04/leetcode-master 已经收录欢迎starfork共同学习一起进步。