描述
image.pngpython方法:
class Solution:
def removeDuplicates(self, nums: List[int]) -> int:
flag = 0
for i in range(len(nums)):
if nums[i] != nums[flag]:
flag += 1
nums[i] = nums[flag]
return flag+1
思路2: 交换,用指针start和last,当nums[start] == val 时交换到最后面,同时last-1,否则start+1
class Solution:
def removeElement(self, nums: List[int], val: int) -> int:
start, last = 0, len(nums)-1
while start <= last:
if nums[start]==val:
nums[start],nums[last] = nums[last], nums[start]
last = last - 1
else:
start = start + 1
return last+1
网友评论