给定一个数组和一个常量 val,删除数组中所有等于 val 的元素,返回新的长度。
备注:
- 不要为另外的数组去开辟新的空间,只能修改原数组,空间复杂度为O(1)。
- 元素的顺序可以改变。
- 数组在返回长度之后的元素无关紧要。
示例:
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.
思路
可以参考数组去重,里面的两个去重方法都适用于本题。
本题以不改变数组长度的第二种方法进行实现:
1、从左到右扫描,维护一个索引,这个索引始终保持为新数组的最后一位。
2、如果扫描到了一个元素不等于val,则将索引+1,且索引对应的值修改为当前元素值。
3、此方法不会改变数组的长度。
python 实现
def removeElement(nums, val):
"""
:type nums: List[int]
:type val: int
:rtype: int
"""
if not nums:
return 0
idx = 0
for num in nums:
if num != val:
nums[idx] = num
idx += 1
return idx
if '__main__' == __name__:
nums = [0,1,2,2,3,0,4,2]
val = 2
print(removeElement(nums, val))

本文介绍了一种高效的算法,用于在不使用额外空间的情况下,从数组中移除指定值的所有实例。该方法通过一次遍历和原地修改实现了O(1)的空间复杂度,详细解释了算法步骤,并提供了Python代码实现。
841

被折叠的 条评论
为什么被折叠?



