【LeetCode 面试经典150题】27. Remove Element 移除元素

27. Remove Element

题目描述

Given an integer array nums and an integer val, remove all occurrences of val in nums in-place. The order of the elements may be changed. Then return the number of elements in nums which are not equal to val.

Consider the number of elements in nums which are not equal to val be k, to get accepted, you need to do the following things:

  • Change the array nums such that the first k elements of nums contain the elements which are not equal to val. The remaining elements of nums are not important as well as the size of nums.
  • Return k.

中文释义

给定一个整数数组 nums 和一个整数 val,就地移除 nums 中所有等于 val 的元素。元素的顺序可以改变。然后返回 nums 中不等于 val 的元素数量。

考虑不等于 valnums 元素数量为 k,为了通过验证,你需要做以下事情:

  • 修改数组 nums,使得 nums 的前 k 个元素包含不等于 val 的元素。nums 的其余元素不重要,同样 nums 的大小也不重要。
  • 返回 k

示例

Example 1

Input : nums = [3,2,2,3], val = 3
Output : 2, nums = [2,2,, ]
Explanation : Your function should return k = 2, with the first two elements of nums being 2.

It does not matter what you leave beyond the returned k (hence they are underscores).

Example 2

Input : nums = [0,1,2,2,3,0,4,2], val = 2
Output : 5, nums = [0,1,4,0,3,, ,_]
Explanation : Your function should return k = 5, with the first five elements of nums containing 0, 0, 1, 3, and 4.

Note that the five elements can be returned in any order.

It does not matter what you leave beyond the returned k (hence they are underscores).

约束条件

  • 0 <= nums.length <= 100
  • 0 <= nums[i] <= 50
  • 0 <= val <= 100

解题思路

方法

使用双指针技巧来移除数组中的特定元素。

步骤

  1. 初始化两个指针

    • index(慢指针):用于在数组中构建不包含特定值的新数组。
    • i(快指针):用于遍历原数组。
  2. 遍历数组

    • 遍历数组时,使用快指针 i 来检查每个元素。
    • 如果当前元素 nums[i] 不等于要移除的值 val,则将其复制到慢指针 index 的当前位置,并递增 index
  3. 更新数组长度

    • 遍历完成后,index + 1 就是新数组的长度,即不包含值 val 的元素数量。

代码实现

cpp 复制代码
class Solution {
public:
    int removeElement(vector<int>& nums, int val) {
        // 在数组中原地移除元素值为val的元素
        // 双指针法
        int index = -1;
        for (int i = 0; i < nums.size(); i++) {
            if (nums[i] != val) {
                nums[++index] = nums[i];
            }
        }
        return index + 1;
    }
};
相关推荐
大佐不会说日语~18 分钟前
JVM垃圾回收机制面试笔记
jvm·笔记·面试
云空22 分钟前
《探索电脑麦克风声音采集多窗口实时可视化技术》
人工智能·python·算法
DoraBigHead25 分钟前
🧠【彻底读懂 reduce】acc 是谁?我是谁?我们要干嘛?
前端·javascript·面试
沧澜sincerely37 分钟前
二分查找【各种题型+对应LeetCode习题练习】
算法·leetcode·二分查找
大千AI助手1 小时前
RLHF:人类反馈强化学习 | 对齐AI与人类价值观的核心引擎
人工智能·深度学习·算法·机器学习·强化学习·rlhf·人类反馈强化学习
小莫分享1 小时前
2023年最新总结,阿里,腾讯,百度,美团,头条等技术面试题目,以及答案,专家出题人分析汇总。
java·后端·面试·职场和发展
byte轻骑兵2 小时前
BLE低功耗设计:从广播模式到连接参数优化的全链路分析与真题解析
面试·职场和发展
满分观察网友z2 小时前
从UI噩梦到导航之梦:一道LeetCode经典题如何拯救了我的项目(116. 填充每个节点的下一个右侧节点指针)
算法
DoraBigHead2 小时前
小哆啦解题记——两数失踪事件
前端·算法·面试
不太可爱的大白2 小时前
Mysql分片:一致性哈希算法
数据库·mysql·算法·哈希算法