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] ]
这个题目如果直接brute force的话,就是O(n^3), 三个for loop。
我们可以用一个for loop 去得到每个num,然后另外用O(n) 时间复杂度的[LeetCode] 1. Two Sum_Easy tag: Hash Table 去找two sum的和是-num。
Note: 因为结果要求是没有重复的list,所以我们先排序,然后在two sum和找num的时候都会去跟之前的数进行比较,来排除重复的组合。
Code: O(n^2)
class Solution: def threeSum(self, nums): def twoSum(nums, left, right, target): ans = [] while left < right: total = nums[left] + nums[right] if total == target: ans.append([-target, nums[left], nums[right]]) left += 1 right -= 1 while left < right and nums[left] == nums[left - 1]: left += 1 while left < right and nums[right] == nums[right + 1]: right -= 1 elif total < target: left += 1 else: right -= 1 return ans ans, n = [], len(nums) for i in range(n - 2): if i and nums[i] == nums[i - 1]: # take out the duplicates continue temp = twoSum(nums, i + 1, n - 1, - nums[i]) if temp: ans += temp return ans
[LeetCode] 15. 3Sum_Medium tag: Array
原文:https://www.cnblogs.com/Johnsonxiong/p/10850996.html