三元組相加得到target

三元組相加得到target

3Sum

  • 給定一個數組,選擇三個元素相加,結果爲target,找出全部符合的三元組git

  • Given an array S of n integers, are there elements a, b, c in S such that a + b + c = 0github

  • Find all unique triplets in the array which gives the sum of zero.數組

Note: The solution set must not contain duplicate triplets.app

For example, given array S = [-1, 0, 1, 2, -1, -4]指針

example 1code

input: [-1, 0, 1, 2, -1, -4]
A solution set is:
[
  [-1, 0, 1],
  [-1, -1, 2]
]

思路

  1. 亂序數組,須要找到全部組合,須要三層循環,複雜度爲O(n³)。排序

  2. 能夠先排序,排序後只須要兩層循環,複雜度爲O(n²)。第一層循環遍歷全部元素,第二層循環因爲數組已經排序,只須要頭尾兩個指針像中間靠攏,一但三個元素相加爲target,則添加此三元組,而後繼續像中間靠攏掃描。three

  3. 須要避免重複的三元組被加入ip

代碼

class Solution(object):
    def threeSum(self, nums):
        """
        :type nums: List[int]
        :rtype: List[List[int]]
        """
        nums.sort()
        ret = []
        for i in range(len(nums) - 2):
            # 避免重複
            if i > 0 and nums[i] == nums[i-1]:
                continue
            j, k = i + 1, len(nums) - 1
            while j < k:
                if nums[i] + nums[j] + nums[k] == 0:
                    ret.append([nums[i], nums[j], nums[k]])
                    j += 1
                    k -= 1
                    # 避免重複
                    while j < k and nums[j] == nums[j - 1]:
                        j += 1
                    while j < k and nums[k] == nums[k + 1]:
                        k -= 1
                elif nums[i] + nums[j] + nums[k] < 0:
                    j += 1
                else:
                    k -= 1
        return ret

本題以及其它leetcode題目代碼github地址: github地址element

相關文章
相關標籤/搜索