LeetCode---15. 3Sum

題目

給定一個數組,找出3個元素a,b,c使得它們的和爲0。找出所有符合該條件的三元組。

Python題解

class Solution:
    def threeSum(self, nums):
        """
        :type nums: List[int]
        :rtype: List[List[int]]
        """
        nums.sort()
        res = []
        for i in range(len(nums) - 2):
            if i == 0 or nums[i] != nums[i - 1]:
                sum2 = 0 - nums[i]
                low, high = i + 1, len(nums) - 1
                while low < high:
                    sum_tmp = nums[low] + nums[high]
                    if sum_tmp == sum2:
                        res.append([nums[i], nums[low], nums[high]])
                        low += 1
                        while low < len(nums) and nums[low] == nums[low - 1]:
                            low += 1
                        high -= 1
                        while high >= 0 and nums[high] == nums[high + 1]:
                            high -= 1
                    elif sum_tmp < sum2:
                        low += 1
                    else:
                        high -= 1
        return res
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章