27. Remove Element

27. Remove Element
前后两个指针,把要删除的元素放在后面,返回前面指针的数就好。
class Solution(object):
def removeElement(self, nums, val):
"""
:type nums: List[int]
:type val: int
:rtype: int
"""
i, j = 0, 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
这种之前是可以的,现在不行了,有用例过不了
[1],1,应该返回[],而上述返回[1]
class Solution(object):
def removeElement(self, nums, val):
"""
:type nums: List[int]
:type val: int
:rtype: int
"""
index = 0
for i in range(len(nums)):
if nums[i] != val:
nums[index] = nums[i]
index += 1
return index