[leetcode]15.三数之和
生活随笔
收集整理的這篇文章主要介紹了
[leetcode]15.三数之和
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
給你一個包含 n 個整數(shù)的數(shù)組?nums,判斷?nums?中是否存在三個元素 a,b,c ,使得?a + b + c = 0 ?請你找出所有和為 0 且不重復的三元組。
注意:答案中不可以包含重復的三元組。
示例 1:
輸入:nums = [-1,0,1,2,-1,-4] 輸出:[[-1,-1,2],[-1,0,1]]?示例 2:
輸入:nums = [] 輸出:[]?示例 3:
輸入:nums = [0] 輸出:[]?提示:
- 0 <= nums.length <= 3000
- -105?<= nums[i] <= 105
雙指針
class Solution:def threeSum(self, nums: List[int]) -> List[List[int]]:ans=[]n=len(nums)nums.sort()for i in range(n):left=i+1right=n-1if nums[i]>0:breakif i>=1 and nums[i]==nums[i-1]:continuewhile left<right:total=nums[i]+nums[left]+nums[right]if total>0:right-=1elif total<0:left+=1else:ans.append([nums[i],nums[left],nums[right]])while left!=right and nums[left]==nums[left+1]:left+=1while left!=right and nums[right]==nums[right-1]:right-=1left+=1right-=1return ans總結(jié)
以上是生活随笔為你收集整理的[leetcode]15.三数之和的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 剑指offer58-||.左旋转字符串
- 下一篇: 黑盒测试的用例设计方法