(双指针)Leetcode283.移动零-替换数字类别+Leetcode15. 三数之和
Leetcode283.移动零
283. 移动零 - 力扣(LeetCode)
方法一:slow代表可以更新的位置,fast是不等于0的位置
class Solution:def moveZeroes(self, nums: List[int]) -> None:"""Do not return anything, modify nums in-place instead."""#快慢指针,不等于0slow更新,最后全部等于0n=len(nums)slow=0for fast in range(n):if nums[fast]!=0:nums[slow]=nums[fast]slow=slow+1for slow in range(slow,n):nums[slow]=0return nums
方法二:原地栈
class Solution(object):def moveZeroes(self, nums):""":type nums: List[int]:rtype: None Do not return anything, modify nums in-place instead."""stack_size = 0for x in nums:if x:nums[stack_size] = x # 把 x 入栈stack_size += 1for i in range(stack_size, len(nums)):nums[i] = 0
Leetcode15. 三数之和
15. 三数之和 - 力扣(LeetCode)
class Solution(object):def threeSum(self, nums):""":type nums: List[int]:rtype: List[List[int]]"""nums.sort()#对原列表排序b = sorted(a)保留原列表results=[]i=0while i<len(nums):if i!=0 and nums[i]==nums[i-1]:i=i+1continue#很重要left=i+1right=len(nums)-1while left<right:# while (left+1)<right and nums[left]==nums[left+1]:# left=left+1# while left<(right-1) and nums[right]==nums[right-1]:# right=right-1# 相等才要去重!if nums[i]+nums[left]+nums[right]==0:results.append([nums[i],nums[left],nums[right]])#左边去重while (left+1)<right and nums[left]==nums[left+1]:left=left+1#右边去重while left<(right-1) and nums[right]==nums[right-1]:right=right-1#找到答案一起收缩left=left+1right=right-1elif nums[i]+nums[left]+nums[right]>0:right=right-1else:# nums[i]+nums[left]+nums[right]<0left=left+1i=i+1return results#-10 -5 -5 -4 -4 -3 0 1 2 2 2 2 5 5