题目:
给你一个数组 nums
和一个值 val
,你需要 原地 移除所有数值等于 val
的元素,并返回移除后数组的新长度。
不要使用额外的数组空间,你必须仅使用 O(1)
额外空间并 原地 修改输入数组。
元素的顺序可以改变。你不需要考虑数组中超出新长度后面的元素。
参考答案1【双指针】:------while循环的写法。
def removeElement(self, nums, val):
"""
:type nums: List[int]
:type val: int
:rtype: int
"""
a = 0
b = 0
while a < len(nums):
if nums[a] != val:
nums[b] = nums[a]
b += 1
a += 1
nums = nums[:b]
return b
参考答案2【双指针】:------for循环的写法。
def removeElement(self, nums, val):
"""
:type nums: List[int]
:type val: int
:rtype: int
"""
slow = 0
for fast in range(len(nums)):
if nums[fast] != val:
nums[slow] = nums[fast]
slow += 1
nums = nums[:slow]
return slow
参考代码3【使用count统计特定元素个数】:
def removeElement(self, nums: List[int], val: int) -> int:
# c = nums.count(val)
# print("c=", c)
# for i in range(c):
# nums.remove(val)
# return len(nums)-c
c = nums.count(val)
result = len(nums)-c
for i in range(c):
nums.remove(val)
return result
本人的漂亮烂代码:
def removeElement(self, nums, val):
"""
:type nums: List[int]
:type val: int
:rtype: int
"""
count = 0
for v in nums:
if v == val:
count += 1
for i in range(count):
nums.remove(val)
反思:
1、关于列表原有的方法或函数,是不是比自己实现更省时省空间?
2、关于列表原有方法和函数,得熟烂于心。
3、看评论说该题有涉及到双指针,python中的双指针标准实现是咋样的?双指针原理呢?
4、双指针:fast指针从左开始移动,用于寻找与val
不一样的值;slow指针也从左开始移动,用于重新赋值;对于有相同元素则覆盖,对于不同元素则重写一次。
5、count()函数可以统计列表中特定元素(值等于val的特定元素)个数。
6、remove()函数可以删除列表中特定元素(值等于val的特定元素)。