LeetCode 题解工作台
移除元素
给你一个数组 nums 和一个值 val ,你需要 原地 移除所有数值等于 val 的元素。元素的顺序可能发生改变。然后返回 nums 中与 val 不同的元素的数量。 假设 nums 中不等于 val 的元素数量为 k ,要通过此题,您需要执行以下操作: 更改 nums 数组,使 nums 的前 …
2
题型
9
代码语言
3
相关题
当前训练重点
简单 · 双·指针·invariant
答案摘要
我们用变量 记录当前不等于 的元素个数。 遍历数组 ,如果当前元素 不等于 ,则将 赋值给 ,并将 自增 。
Interview AiBoxInterview AiBox 实时 AI 助手,陪你讲清 双·指针·invariant 题型思路
题目描述
给你一个数组 nums 和一个值 val,你需要 原地 移除所有数值等于 val 的元素。元素的顺序可能发生改变。然后返回 nums 中与 val 不同的元素的数量。
假设 nums 中不等于 val 的元素数量为 k,要通过此题,您需要执行以下操作:
- 更改
nums数组,使nums的前k个元素包含不等于val的元素。nums的其余元素和nums的大小并不重要。 - 返回
k。
用户评测:
评测机将使用以下代码测试您的解决方案:
int[] nums = [...]; // 输入数组
int val = ...; // 要移除的值
int[] expectedNums = [...]; // 长度正确的预期答案。
// 它以不等于 val 的值排序。
int k = removeElement(nums, val); // 调用你的实现
assert k == expectedNums.length;
sort(nums, 0, k); // 排序 nums 的前 k 个元素
for (int i = 0; i < actualLength; i++) {
assert nums[i] == expectedNums[i];
}
如果所有的断言都通过,你的解决方案将会 通过。
示例 1:
输入:nums = [3,2,2,3], val = 3 输出:2, nums = [2,2,_,_] 解释:你的函数应该返回 k = 2, 并且 nums 中的前两个元素均为 2。 你在返回的 k 个元素之外留下了什么并不重要(因此它们并不计入评测)。
示例 2:
输入:nums = [0,1,2,2,3,0,4,2], val = 2 输出:5, nums = [0,1,4,0,3,_,_,_] 解释:你的函数应该返回 k = 5,并且 nums 中的前五个元素为 0,0,1,3,4。 注意这五个元素可以任意顺序返回。 你在返回的 k 个元素之外留下了什么并不重要(因此它们并不计入评测)。
提示:
0 <= nums.length <= 1000 <= nums[i] <= 500 <= val <= 100
解题思路
方法一:一次遍历
我们用变量 记录当前不等于 的元素个数。
遍历数组 ,如果当前元素 不等于 ,则将 赋值给 ,并将 自增 。
最后返回 即可。
时间复杂度 ,空间复杂度 。其中 为数组 的长度。
class Solution:
def removeElement(self, nums: List[int], val: int) -> int:
k = 0
for x in nums:
if x != val:
nums[k] = x
k += 1
return k
复杂度分析
| 指标 | 值 |
|---|---|
| 时间 | Depends on the final approach |
| 空间 | Depends on the final approach |
面试官常问的追问
外企场景- question_mark
Is the candidate able to implement an in-place algorithm that avoids extra space usage?
- question_mark
Does the candidate use a two-pointer approach efficiently to solve the problem?
- question_mark
Is the candidate aware of how to handle edge cases, such as when the array is empty?
常见陷阱
外企场景- error
Misunderstanding the requirement to modify the array in-place, resulting in unnecessary space allocation.
- error
Incorrectly updating the array while traversing it, which can lead to overwriting values before they are used.
- error
Failing to properly track the position of the second pointer, leading to an incorrect final count.
进阶变体
外企场景- arrow_right_alt
Remove all occurrences of multiple values in the array.
- arrow_right_alt
Remove values from a sorted array while maintaining the sorted order.
- arrow_right_alt
Implement the solution using a single pointer, modifying the array at the current index.