https://leetcode-cn.com/problems/remove-element/description/
遍历一遍遇到要删除的值跳过,将数组重写一遍,这样的最快的。
class Solution:
def removeElement(self, nums, val):
"""
:type nums: List[int]
:type val: int
:rtype: int
"""
if len(nums) == 0:
return 0;
j=0
for i in range(0,len(nums)):
if nums[i] != val :
nums[j] = nums[i]
j = j + 1
return j
这个是真没想到。。。。
自己写的方法是,有点类似于快排partition操作,用两个指针,前面遇到要删除的元素时,将数组尾部不被删除的移到前面,直到i>j结束循环
class Solution:
def removeElement(self, nums, val):
"""
:type nums: List[int]
:type val: int
:rtype: int
"""
i= 0
j= len(nums)-1
count = 0
s = 0
while(1):
if(i>j):
break
if nums[i]==val:
count+=1
while(nums[j]==val and j>i):
count+=1
j=j-1
nums[i]=nums[j]
j=j-1
i+=1
else:
i+=1
return len(nums)-count