1.题目描述
[15] 三数之和
https://leetcode-cn.com/problems/3sum/description/
algorithms
Medium (21.76%)
Total Accepted: 46.5K
Total Submissions: 213.6K
Testcase Example: ‘[-1,0,1,2,-1,-4]’
给定一个包含 n 个整数的数组 nums,判断 nums 中是否存在三个元素 a,b,c ,使得 a + b + c = 0
?找出所有满足条件且不重复的三元组。
注意:答案中不可以包含重复的三元组。
例如, 给定数组 nums = [-1, 0, 1, 2, -1, -4],
满足要求的三元组集合为:
[
[-1, 0, 1],
[-1, -1, 2]
]
2.解答
-
因暴力法超时,故想办法做出优化,可先对数组进行排序,设立i, j, k三个指针,i从左向右依次移动,j和k分别指向i右边剩余的头和尾元素,根据约束条件,j和k逐步靠拢,i遍历结束即得到解。
其中有几个优化点:i指向元素>=0或者k指向元素<=0时可停止没必要继续移动i和k;排序后遇到连续几个相等的元素,指针跳过即可。
class Solution: def threeSum(self, nums: List[int]) -> List[List[int]]: nums.sort() res = [] length = len(nums) for i in range(length): if nums[i] <= 0 : if nums[i] > nums[i - 1] or i ==0: j, k = i + 1, length - 1 while nums[k] >= 0 and j < k: sum = nums[i] + nums[j] + nums[k] if sum > 0: k -= 1 elif sum < 0: j += 1 else: res.append([nums[i], nums[j], nums[k]]) k -= 1 j += 1 while nums[j] == nums[j - 1] and j < k: j += 1 while nums[k] == nums[k + 1] and j < k: k -= 1 else: break return res
-
转leetcode别人的代码,先将nums中的元素做了计数存在了d这个dict中,然后对nums进行了正负元素划分,双层循环遍历,查找第三个元素是否存在于d,这里注意:遇到三个元素中有两个相等的需要验证确实存在两个。其实这里的pos和neg可以是set类型,去重后效率更高。
class Solution: def threeSum(self, nums: List[int]) -> List[List[int]]: d = {} for val in nums: d[val] = d.get(val, 0) + 1 pos = [x for x in d if x > 0] neg = [x for x in d if x < 0] res = [] if d.get(0, 0) > 2: res.append([0, 0, 0]) for x in pos: for y in neg: s = -(x + y) if s in d: if s == x and d[x] > 1: res.append([x, x, y]) elif s == y and d[y] > 1: res.append([x, y, y]) elif y < s < x: res.append([x, y, s]) return res