题目
给你一个数组
和一个值
,你需要 原地 移除所有数值等于
的元素,并返回移除后数组的新长度。
不要使用额外的数组空间,你必须仅使用
额外空间并 原地 修改输入数组。
元素的顺序可以改变。你不需要考虑数组中超出新长度后面的元素。
解题
def remove_element(nums, val):
# 初始化新数组索引
new_index = 0
for current_index in range(len(nums)):
if nums[current_index] != val:
nums[new_index] = nums[current_index]
new_index += 1
return new_index
# 测试例子
nums = [3, 2, 2, 3]
value = 3
new_length = remove_element(nums, value)
print("新数组的长度:", new_length)
print("移除后的数组:", nums[:new_length])
新数组的长度: 2
移除后的数组: [2, 2]