Array
027. Remove Element
Given an array nums and a value val, remove all instances of that value in-place and return the new length.
Do not allocate extra space for another array, you must do this by modifying the input array in-place with O(1) extra memory.
即
1.去掉数组中等于val的元素
2.返回新数组的长度
3.不要额外空间
Solutions
当val在nums中时,去掉它
class Solution:
def removeElement(self, nums, val):
"""
:type nums: List[int]
:type val: int
:rtype: int
"""
while val in nums:
nums.remove(val)
return len(nums)
或者和3sum closest一样利用两个指标
def removeElement1(self, A, elem):
i, last = 0, len(A) - 1
while i <= last:
if A[i] == elem:
A[i], A[last] = A[last], A[i]
last -= 1
else:
i += 1
return last + 1
网友评论