1. 程式人生 > >三數之和 leetcode python程式設計

三數之和 leetcode python程式設計

Given an array nums of n integers, are there elements abc in nums such that a + b + c = 0? Find all unique triplets in the array which gives the sum of zero.

Note:The solution set must not contain duplicate triplets.

給定一個包含 n 個整數的陣列 nums,判斷 nums 中是否存在三個元素 a,b,c ,使得 a + b + c = 0 ?找出所有滿足條件且不重複的三元組。

注意:答案中不可以包含重複的三元組。

例如, 給定陣列 nums = [-1, 0, 1, 2, -1, -4],

滿足要求的三元組集合為:
[
  [-1, 0, 1],
  [-1, -1, 2]
]

程式碼:

class Solution(object):
    def threeSum(self, nums):
        """
        :type nums: List[int]
        :rtype: List[List[int]]
        """
        ret_list = []
        countNumberSet = {}
        countNumberSet = self.countNumber(nums)
        for key, value in countNumberSet.items():
            if(key == 0 and value>=3): 
                ret_list.append([0,0,0])
            #下面三個條件的順序也是有技巧的,雖然都是與操作,但是我們要考慮短路思想
            #下面如果把 key != 0放到第一位,演算法就會超時!!至少我提交的時候是這樣的
            elif(value >= 2 and key !=0 and (0-key-key) in nums):
                temp = [key, key, 0-key-key]
                temp.sort()
                ret_list.append(temp)
        #去掉所有重複資料,保證資料的唯一性
        nums = list(set(nums))
        if(len(nums) <= 2):
            pass
        else:
            nums.sort()
            for i in range(len(nums)):
                left = i
                middle = i + 1
                right = len(nums) - 1
                #如果左指標所指向的資料大於0,則說明後面所有的資料都大於0,則停止
                #如果右指標所指向的資料少於0,則說明前面所有的資料都小於0,則停止
                if(nums[left] > 0 or nums[right] < 0):
                    break;
                while(middle < right):
                    if(nums[left] + nums[middle] + nums[right] == 0):
                        ret_list.append([nums[left], nums[middle], nums[right]])
                        middle += 1
                        right -= 1
                    elif(nums[left] + nums[middle] + nums[right] > 0):
                        right -= 1
                    else:
                        middle += 1
        return ret_list
    
    def countNumber(self, nums):
        countNumberSet = {}
        for i in nums:
            if i not in countNumberSet.keys():
                countNumberSet[i] = 0
            countNumberSet[i] += 1
        return countNumberSet

成功

顯示詳情

執行用時: 1440 ms, 在3Sum的Python3提交中擊敗了30.55% 的使用者

提交時間 狀態 執行用時 語言
幾秒前 通過 1440 ms python3
2 分鐘前 N/A python3