思路见注释。
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 if len(nums) == 0: 9 return 0 10 # 双指针 11 i, j = 0, len(nums) - 1 12 while i < j: 13 # j指向的等于val,j前移 14 if nums[j] == val: 15 j -= 1 16 continue 17 # 如果i指向的等于val,交换i和j的值,j前移 18 if nums[i] == val: 19 nums[i], nums[j] = nums[j], nums[i] 20 j -= 1 21 # i每一趟都后移 22 i += 1 23 print(nums, i, j) 24 if nums[i] == val: 25 return len(nums[:i]) 26 else: 27 return len(nums[:i]) + 1 28 29 if __name__ == '__main__': 30 solution = Solution() 31 print(solution.removeElement(nums=[0, 1, 2, 2, 3, 2, 4, 2, 5], val=2)) 32 print(solution.removeElement(nums=[], val=5))