一、题目
Given an array S of n integers, are there elements a, b, c in S such that a + b + c = 0? Find all unique triplets in the array which gives the sum of zero.
Note:
- Elements in a triplet (a,b,c) must be in non-descending order. (ie, a ≤ b ≤ c)
- The solution set must not contain duplicate triplets.
For example, given array S = {-1 0 1 2 -1 -4}, A solution set is: (-1, 0, 1) (-1, -1, 2) 二、思路我的思路一直很简单,当初在做2Sum的时候,就是把求和问题变成了一个查找问题,定下一个数a,去找target-a在不在剩余的数里。3Sum也这么做,但是效率明显低多了。而且这题让输出所有可能的答案组合,牵扯到重复的问题。做法还是按照变求和为查询,定下a,b,找target-(a+b),唯一做的优化就是用哈希表存下已有的(a,b),这样不至于做重复的查找。但是这样毕竟不是办法,以后做4sum就要4层循环了,不是个事。看别人的答案,是从两边往中间找,这个挺好的。准备在3Sum Closet里试一下这种方法。 三、代码
1 class Solution: 2 # @param {integer[]} nums 3 # @return {integer[][]} 4 def threeSum(self, nums): 5 nums.sort() 6 passed_list = [] 7 result = [] 8 record = {} 9 result_dict = {} 10 if len(nums) < 3: 11 return [] 12 else: 13 for i in range(len(nums)): 14 for j in range(i + 1, len(nums)): 15 a = nums[i] 16 b = nums[j] 17 if (a, b) in record: 18 pass 19 else: 20 record[(a, b)] = 0 21 target = 0 - a - b 22 if target in nums[j + 1:]: 23 passed_list.append(a) 24 passed_list.append(b) 25 passed_list.append(target) 26 if str(passed_list) in result_dict: 27 passed_list = [] 28 pass 29 else: 30 result.append(passed_list) 31 result_dict[str(passed_list)] = 0 32 passed_list = [] 33 return result
四、总结
准备把n-sum这类问题全部做完,然后总结一下这类题的规律。
时间: 2024-12-15 15:21:01