【LeetCode每天一題】3Sum(三數之和)
阿新 • • 發佈:2019-04-02
family 第一個 contain 直接 spa 判斷 sort 當前 The
Given an array nums
of n integers, are there elements a, b, c 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.
Example: Given array nums = [-1, 0, 1, 2, -1, -4], A solution set is: [ [-1, 0, 1], [-1, -1, 2] ]
思路
我們先對數組進行排序,然後從第一個數字開始查找, 然後在後面的數組中查找是否有滿足條件的(使用兩個指針一個指向開頭,一個指向尾部開始遍歷)。時間復雜度為O(n*n), 空間復雜度為O(1)。
圖示步驟
解決代碼
1 class Solution(object):
2 def threeSum(self, nums):
3 nums.sort()
4 length = len(nums)
5 res_list = []
6 for i in range(length - 2): # 以此下標的數字和其他進行匹配
7 if i > 0 and nums[i] == nums[i - 1]: # 如果和上一個數字相等,直接返回。 因為上一次已經查找過
8 continue
9 start, end = i + 1, length-1 # 在後面的數組中設置起始指針和尾部指針
10 while start < end:
11 tem = nums[i] + nums[start] + nums[end]
12 if tem == 0: # 如果三個數字之和等於0,將其進行添加
13 res_list.append([nums[i], nums[start], nums[end]])
14
15 while start < end and nums[start] == nums[start+1]: # 判斷start下一個數字和當前數字是否相等,相等下移一位。不然會添加進重復的元素
16 start += 1
17 while start < end and nums[end] == nums[end-1]: # 判斷end上一個數字和當前數字是否相等,相等則跳過。
18 end -= 1
19 start += 1
20 end -= 1
21 elif tem < 0: # 和小於 0 的話,start進位
22 start += 1
23 else: # 和大於0的話,end減一
24 end -= 1
25 return res_list
【LeetCode每天一題】3Sum(三數之和)