1 class Solution(object): 2 def removeElement(self, nums, val): 3 """ 4 :type nums: List[int] 5 :type val: int 6 :rtype: int 7 """ 8 # 双指针法,left从前往后定位val,right从后往前把非val换到left指向的val位置 9 left = 0 10 right = len(nums)-1 11 while(left<right):# 还没遍历完数组时进入循环 12 if nums[left]==val: 13 if nums[right]!=val: 14 nums[left] = nums[right] 15 left += 1 16 right -= 1 17 else: 18 right -= 1 19 else: 20 left += 1 21 # 判断跳出循环时,left和right的大小关系,返回left相关 22 # left指向要保留 23 if left==right and val!=nums[left]: 24 return left+1 25 # right<left或left==right,nums[left]==val,删除 26 else: 27 return left
标签:right,val,nums,int,力扣,数组,指针,left From: https://www.cnblogs.com/shi-yi/p/17268264.html