给你一个数组 nums 和一个值 val,你需要 原地 移除所有数值等于 val 的元素,并返回移除后数组的新长度。

不要使用额外的数组空间,你必须仅使用 O(1) 额外空间并 原地 修改输入数组。

元素的顺序可以改变。你不需要考虑数组中超出新长度后面的元素。

说明:

为什么返回数值是整数,但输出的答案是数组呢?

请注意,输入数组是以「引用」方式传递的,这意味着在函数里修改输入数组对于调用者是可见的。

你可以想象内部操作如下:

  1. // nums 是以“引用”方式传递的。也就是说,不对实参作任何拷贝
  2. int len = removeElement(nums, val);
  3. // 在函数里修改输入数组对于调用者是可见的。
  4. // 根据你的函数返回的长度, 它会打印出数组中 该长度范围内 的所有元素。
  5. for (int i = 0; i < len; i++) {
  6. print(nums[i]);
  7. }

示例 1:

  1. Input: nums = [3,2,2,3], val = 3
  2. Output: 2, nums = [2,2]
  3. Explanation: Your function should return length = 2, with the first two elements of nums being 2.
  4. It doesn't matter what you leave beyond the returned length. For example if you return 2 with nums = [2,2,3,3] or nums = [2,2,0,0], your answer will be accepted.

示例 2:

  1. Input: nums = [0,1,2,2,3,0,4,2], val = 2
  2. Output: 5, nums = [0,1,4,0,3]
  3. Explanation: Your function should return length = 5, with the first five elements of nums containing 0, 1, 3, 0, and 4. Note that the order of those five elements can be arbitrary. It doesn't matter what values are set beyond the returned length.

提示:

  • 0 ≤ nums.length ≤ 10;
  • 0 ≤ nums[i] 50;
  • 0 ≤ val ≤ 100

思路

本题有两个思路,一个是暴力穷举,一个是双指针。双指针我们留到后面的专题再演示。

对于暴力穷举,借用代码随想录的示意图:

移除元素-27 - 图1

代码

Cpp:

  1. // 4ms, 8.6MB
  2. class Solution {
  3. public:
  4. int removeElement(vector<int>& nums, int val) {
  5. if( nums.size() == 0 ) return 0;
  6. int total_size = nums.size();
  7. for(int i = 0; i < total_size; i++) {
  8. if( nums[i] == val ) {
  9. for(int j = i+1; j < total_size; j++) {
  10. nums[j-1] = nums[j];
  11. }
  12. i -= 1;
  13. total_size -= 1;
  14. }
  15. }
  16. return total_size;
  17. }
  18. };

Rust:

  1. // 0ms, 1.9MB
  2. impl Solution {
  3. pub fn remove_element(nums: &mut Vec<i32>, val: i32) -> i32 {
  4. if nums.len() == 0 { return 0; }
  5. let mut total_size = nums.len();
  6. let mut i = 0;
  7. while i < total_size {
  8. if nums[i] == val {
  9. for j in i+1 .. total_size {
  10. nums[j-1] = nums[j];
  11. }
  12. i -= 1;
  13. total_size -= 1;
  14. }
  15. i += 1;
  16. }
  17. total_size as i32
  18. }
  19. }