# 引言

题目链接:https://leetcode.com/problems/remove-element/

# 题目大意

给定数组 nums 和值 val, 在适当位置删除该值的所有实例并返回新长度。

Hint: 不要为另一个数组分配额外的空间,必须通过使用 O (1) 额外内存修改输入数组来实现此目的。元素的顺序可以改变.

  • Example
Given nums = [3,2,2,3], val = 3,
Your function should return length = 2, with the first two elements of nums being 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.

# 题解

# 一句话题解

利用原数组,遍历的同时将遍历数据放到元素组头部,跳过数值等于给定数值 val 的所有元素即可

# 复杂度

时间复杂度 O(n)

空间复杂度 O(1)

# AC 代码

c++ 版本

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

go 版本

func removeElement(nums []int, val int) int {
	var res int
	for i := 0; i < len(nums); i++ {
		if nums[i] != val {
			nums[res] = nums[i]
			res++
		}
	}
	return res
}
更新于 阅读次数