python 三数之和
生活随笔
收集整理的這篇文章主要介紹了
python 三数之和
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
三數(shù)之和
給你一個包含 n 個整數(shù)的數(shù)組 nums,判斷 nums 中是否存在三個元素 a,b,c ,使得 a + b + c = 0 ?請你找出所有和為 0 且不重復(fù)的三元組。注意:答案中不可以包含重復(fù)的三元組。示例 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]]:n = len(nums)nums.sort()ans = list()# 枚舉 afor first in range(n):# 需要和上一次枚舉的數(shù)不相同if first > 0 and nums[first] == nums[first - 1]:continue# c 對應(yīng)的指針初始指向數(shù)組的最右端third = n - 1target = -nums[first]# 枚舉 bfor second in range(first + 1, n):# 需要和上一次枚舉的數(shù)不相同if second > first + 1 and nums[second] == nums[second - 1]:continue# 需要保證 b 的指針在 c 的指針的左側(cè)while second < third and nums[second] + nums[third] > target:third -= 1# 如果指針重合,隨著 b 后續(xù)的增加# 就不會有滿足 a+b+c=0 并且 b<c 的 c 了,可以退出循環(huán)if second == third:breakif nums[second] + nums[third] == target:ans.append([nums[first], nums[second], nums[third]])return ans總結(jié)
以上是生活随笔為你收集整理的python 三数之和的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: python两数之和(hash 表)
- 下一篇: 水鱼的第一篇博客