27 移除元素——Easy

  • 链接:https://leetcode-cn.com/problems/remove-element/

  • 思路:与 26 题的解法十分相似

    • 设置两个指针 \(fast\)\(slow\),其中 \(slow\) 是慢指针,\(fast\) 是快指针
    • \(nums[fast]\) 与给定的值相等时,递增 \(fast\) 以跳过该元素
    • \(nums[fast] \neq val\) ,交换 \(nums[fast]\)\(nums[slow]\) ,并同时递增两个索引
    • 重复这一过程,直到 \(fast\) 到达数组的末尾,数组的新长度为 \(slow\)
  • Code

class Solution {
public:
    int removeElement(vector<int>& nums, int val) {
        int slow = 0;
        for (int fast = 0; fast < nums.size(); ++fast) {
            if (nums[fast] != val) {
                swap(nums[fast], nums[slow++]);
            }
        }
        return slow;
    }
};
  • 复杂度分析
    • 时间复杂度:\(O(n)\),假设数组总共有 \(n\) 个元素,\(fast\)\(slow\) 至多遍历 \(n\)
    • 空间复杂度:\(O(1)\)

猜你喜欢

转载自www.cnblogs.com/bky-hbq/p/13171864.html
今日推荐