题目
解题
使用while循环
计算val在数组中出现的次数nums.count(val),当nums.count(val)>0时,移除val 则次数减1。所以使用while循环
代码如下:
class Solution(object):
def removeElement(self, nums, val):
"""
:type nums: List[int]
:type val: int
:rtype: int
"""
while nums.count(val)!=0:
nums.remove(val)
return len(nums)
快慢指针
在数组创建快慢指针。慢指针i,快指针j。
慢指针i用来记录数组中与目标函数不相等元素的个数;快指针j用来遍历数组中的元素
当j与目标元素不相等时,将数组中的元素依次取代为j,i+=1。当j与目标元素相等时,j向后移动,i不变。
class Solution(object):
def removeElement(self, nums, val):
"""
:type nums: List[int]
:type val: int
:rtype: int
"""
i=0
for j in nums:
if j!=val:
nums[i]=j
i+=1
return i