【题目】:
Given an array and a value, 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:
Given nums = [3,2,2,3], val = 3, Your function should return length = 2, with the first two elements of nums being 2.
【参考】:参考资料
【思路】:需要限制在O(1)的额外空间
1.使用两个指针i和j,i是慢指针,j是快指针。当nums[j]等于val时,j继续往下走,直到走到nums[j]不等于val,此时将nums[j]的值赋给nums[i],并将i和j同时+1。总得来说,就是通过j指针来遍历nums列表,找到的不等于val的值从头开始放置在列表中。i的值就是删除val后所有的剩余元素长度
2.考虑像[1,2,3,4,5],val=5这样的情况,1-4不需要移动。所以第一种思路的做法会引起额外的移动开销。由于数组中的元素顺序是可以被改变的,因此如果当前元素的值与val相同,就与nums中的最后一个元素进行交换,再从当前位置进行比较;若当前元素的值与val不相同,则直接往下走即可。
【Python代码1】:
class Solution:
def removeElement(self, nums, val):
"""
:type nums: List[int]
:type val: int
:rtype: int
"""
i, j = 0, 0
length = len(nums)
while j < length:
if val == nums[j]:
j += 1
else:
nums[i] = nums[j]
i += 1
j += 1
return i
【Python代码2】:
class Solution:
def removeElement(self, nums, val):
"""
:type nums: List[int]
:type val: int
:rtype: int
"""
i = 0
length = len(nums)
while i < length:
if nums[i] == val:
nums[i] = nums[length-1]
length -= 1
else:
i += 1
return length