|
| 1 | +from typing import List |
| 2 | + |
| 3 | +class Solution: |
| 4 | + """ |
| 5 | + 15. 三数之和 |
| 6 | + https://leetcode-cn.com/problems/3sum/ |
| 7 | + 给你一个包含 n 个整数的数组 nums,判断 nums 中是否存在三个元素 a,b,c ,使得 a + b + c = 0 ?请你找出所有满足条件且不重复的三元组。 |
| 8 | + 注意:答案中不可以包含重复的三元组。 |
| 9 | + """ |
| 10 | + # 双指针 |
| 11 | + def threeSum(self, nums: List[int]) -> List[List[int]]: |
| 12 | + # 若数组长度小于3,则返回空数组 |
| 13 | + res = [] |
| 14 | + n = len(nums) |
| 15 | + if n < 3: |
| 16 | + return res |
| 17 | + |
| 18 | + # 对数组进行排序 |
| 19 | + nums.sort() |
| 20 | + for i in range(n-2): |
| 21 | + # 若 i 大于 0 则终止循环,返回结果 |
| 22 | + if nums[i] > 0: |
| 23 | + return res |
| 24 | + |
| 25 | + |
| 26 | + # 对于重复元素,直接跳过 |
| 27 | + if i > 0 and nums[i] == nums[i-1]: |
| 28 | + continue |
| 29 | + |
| 30 | + # 声明左指针 L=i+1, 右指针 R=n-1, |
| 31 | + l = i + 1 |
| 32 | + r = n - 1 |
| 33 | + |
| 34 | + while(l < r): |
| 35 | + num = nums[i] + nums[l] + nums[r] |
| 36 | + # 若 nums[i] + nums[L] + nums[R] = 0 |
| 37 | + if num == 0: |
| 38 | + res.append([nums[i], nums[l], nums[r]]) |
| 39 | + l += 1 |
| 40 | + while nums[l] == nums[l-1] and l < r: |
| 41 | + l += 1 |
| 42 | + r -= 1 |
| 43 | + while nums[r] == nums[r+1] and l < r: |
| 44 | + r -= 1 |
| 45 | + # 若和小于0,则说明 nums[L] 小了,L 向右移 |
| 46 | + elif num < 0: |
| 47 | + l += 1 |
| 48 | + # 若和大于0,则说明 nums[R] 打了,R 向左移 |
| 49 | + else: |
| 50 | + r -= 1 |
| 51 | + return res |
| 52 | + |
| 53 | + # 暴力破解 |
| 54 | + def threeSumByForce(self, nums: List[int]) -> List[List[int]]: |
| 55 | + res = [] |
| 56 | + nums.sort() |
| 57 | + for i in range(len(nums) - 2): |
| 58 | + if i > 0 and nums[i] == nums[i - 1]: |
| 59 | + continue |
| 60 | + for j in range(i + 1, len(nums) - 1): |
| 61 | + if j > i + 1 and nums[j] == nums[j - 1]: |
| 62 | + continue |
| 63 | + for m in range(j + 1, len(nums)): |
| 64 | + if m > j + 1 and nums[m] == nums[m - 1]: |
| 65 | + continue |
| 66 | + if nums[i] + nums[j] + nums[m] == 0: |
| 67 | + res.append([nums[i], nums[j], nums[m]]) |
| 68 | + return res |
| 69 | + |
| 70 | + |
| 71 | +so = Solution() |
| 72 | +print(so.threeSum([-1,0,1,2,-1,-4])) |
| 73 | +print(so.threeSum([0, 0, 0, 0])) |
| 74 | +print(so.threeSum([-2,0,0,2,2])) |
| 75 | + |
0 commit comments