【每日一题】27. Remove Element

时间:2022-07-22
本文章向大家介绍【每日一题】27. Remove Element,主要内容包括其使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

题目描述

Given an array nums and a value val, remove all instances of that value in-place and return the new length.

Do not allocate extra space for another array, you must do this by modifying the input array in-place with O(1) extra memory.

The order of elements can be changed. It doesn’t matter what you leave beyond the new length.

Example 1:

Given nums = [3,2,2,3], val = 3,

Your function should return length = 2, with the first two elements of nums being 2.

It doesn't matter what you leave beyond the returned length.

Example 2:

Given nums = [0,1,2,2,3,0,4,2], val = 2,

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.

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

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

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

题解

这道题类似于上一题26. Remove Duplicates from Sorted Array;不过这里给定的数组没有表明是有序的,但做法大同小异:

  • 声明两个指针,一个指针指向不包含val的数组;另一个指向原数组的第一个元素;
  • 依次遍历,如果当前值等于val,跳过;如果不等于,将这个元素划分到子数组中,
  • 最后不包含val的子数组的下标idx表明数组的右边界,因此返回idx+1即可。

Code

class Solution {
public:
    int removeElement(vector<int>& nums, int val) {
        int idx = -1;
        
        for (int i=0; i< nums.size(); i++){
            if (nums[i] != val)
                nums[++idx] = nums[i];
        }
        
        return idx + 1;
    }
};