LeetCode 27 Remove Element 移除元素
给定一个数组 nums 和一个值 val,你需要原地移除所有数值等于 val 的元素,返回移除后数组的新长度。
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.
The order of elements can be changed. It doesn’t matter what you leave beyond the new length.
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.
class Solution 1:
def removeElement(self, nums: List[int], val: int) -> int:
while val in nums:
nums.remove(val)
return len(nums)
class Solution 2:
def removeElement(self, nums: List[int], val: int) -> int:
i = 0
for num in nums:
if num != val:
nums[i] = num
i += 1
return i
单向遍历数组元素,遍历到的元素值不等于val则从左到右依次填充覆盖nums列表,如果发现等于val了则位置留着给后面不等于val的值填充。所以最后nums[i]前面是剔除等于val值排列的,后面则还是nums原来的值。
class Solution 3:
def removeElement(self, nums, val):
i = 0
j = len(nums) - 1
while i <= j:
if nums[i] == val:
nums[i], nums[j] = nums[j], nums[i]
j -= 1
else:
i += 1
return j + 1