题目:给定一个数值nums和一个值val,原地移除所有数值等于val的元素,并返回移除后数组的新长度。
(不要使用额外数组空间,你必须仅使用额外空间并原地修改输入数组。)
例:
给定 nums = [3,2,2,3], val = 3,函数应该返回新的长度 2, 并且 nums 中的前两个元素均为 2。你不需要考虑数组中超出新长度后面的元素。
给定 nums = [0,1,2,2,3,0,4,2], val = 2,函数应该返回新的长度 5, 并且 nums 中的前五个元素为 0, 1, 3, 0, 4。注意这五个元素可为任意顺序。你不需要考虑数组中超出新长度后面的元素。
题解:
一、双指针
def removeElement(nums: List[int], val: int) -> int:if len(nums) == 0:return 0i = 0for j in range(len(nums)):if nums[j] != val:nums[i] = nums[j]i += 1else:continuereturn i作者:qian-chen-yi-meng-k链接:https://leetcode-cn.com/problems/remove-element/solution/shuang-zhi-zhen-fa-by-qian-chen-yi-meng-k/来源:力扣(LeetCode)著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
知识点:
快慢双指针
通常可以用来原地改变数组:快指针用来遍历数组,慢指针根据快指针遍历的结果做出相应处理。
class Solution:
def removeElement(self, nums: List[int], val: int) -> int:
if not nums:return 0
slow = 0
n = len(nums)
fast = n - 1
while slow < fast:
while slow < fast and nums[slow] != val:
slow += 1
while slow < fast and nums[fast] == val:
fast -= 1
nums[slow],nums[fast] = nums[fast],nums[slow]
slow += 1
fast -= 1
res = 0
#print(nums,slow,fast)
#return fast + 1
for i in range(n):
if nums[i] == val:
return res
res += 1
作者:powcai
链接:https://leetcode-cn.com/problems/remove-element/solution/yi-chu-yuan-su-by-powcai/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
知识点:
对撞双指针
通常可以用来原地改变数组:正指针和反指针分别用来寻找不同的目标,最终实现换位或其它操作。
二、python内置方法
class Solution:
def removeElement(self, nums: List[int], val: int) -> int:
try:
while True:
nums.remove(val)
except:
return len(nums)
作者:xian-ren-mian
链接:https://leetcode-cn.com/problems/remove-element/solution/-by-xian-ren-mian-2/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
知识点:
list.remove(a)
从list中移除值为a的元素。
class Solution:
def removeElement(self, nums, val):
for i in range(len(nums) - 1, -1, -1):
if nums[i] == val:
nums.pop(i)
return len(nums)
作者:multiplierzhang
链接:https://leetcode-cn.com/problems/remove-element/solution/27-yi-chu-yuan-su-by-multiplierzhang/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
知识点:
list.pop(a)
从list中移除索引为a的元素。
remove()和pop()的区别:
x=[1,2,3,4,5,6]
x.pop(5)
x=[1, 2, 3, 4, 5]
x=[1,2,3,4,5,6]
x.remove(5)
x=[1, 2, 3, 4, 6]
