[LeetCode] 15. 3Sum_Medium tag: Array
2019-05-12 03:51 Johnson_强生仔仔 阅读(226) 评论(0) 编辑 收藏 举报
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: List[int]) -> List[List[int]]: nums.sort() ans, n = [], len(nums) if n < 3: return ans for i in range(n - 2): if i == 0 or nums[i] != nums[i - 1]: self.twoSum(nums, i + 1, n - 1, - nums[i], ans) return ans def twoSum(self, nums, start, end, target, ans): while start < end: total = nums[start] + nums[end] if total < target: start += 1 elif total > target: end -= 1 else: ans.append([-target, nums[start], nums[end]]) start += 1 end -= 1 while start < end and nums[start] == nums[start - 1]: start += 1 while start < end and nums[end] == nums[end + 1]: end -= 1