Leetcode python《热题 HOT 100》15. 三数之和
生活随笔
收集整理的這篇文章主要介紹了
Leetcode python《热题 HOT 100》15. 三数之和
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
Leetcode python 之 《熱題 HOT 100》:https://leetcode-cn.com/problemset/hot-100/
15. 三數之和
給定一個包含 n 個整數的數組 nums,判斷 nums 中是否存在三個元素 a,b,c ,使得 a + b + c = 0 ?找出所有滿足條件且不重復的三元組。
注意:答案中不可以包含重復的三元組。
例如, 給定數組 nums = [-1, 0, 1, 2, -1, -4],
滿足要求的三元組集合為: [ [-1, 0, 1], [-1, -1, 2] ]
我的答案1:
''' 版本: Python 2.7.12 ''' class Solution(object):def threeSum(self, nums):""":type nums: List[int]:rtype: List[List[int]]"""nums1=sorted(nums)list1=[]for a in range(0,len(nums1)-2):if nums1[a]>0:breakfor b in range(a+1,len(nums1)-1):if nums1[a]+nums1[b]>0:breakfor c in range(b+1,len(nums1)):if nums1[c]<0 or nums1[b]+nums1[c]<0:continueif nums1[a]+nums1[b]+nums1[c]==0 and not [nums1[a],nums1[b],nums1[c]] in list1: list1.append([nums1[a],nums1[b],nums1[c]]) return list1評價:
超出時間限制
我的答案2:
總結
以上是生活随笔為你收集整理的Leetcode python《热题 HOT 100》15. 三数之和的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: python 在python的class
- 下一篇: Intel Realsense D435