三数之和

三数之和

1、题目

image-20240214233202251

2、题解

思想:排序+双指针

​ 本题与两数之和有类似的思想,都是使用双指针来进行解题。不同的是该题要求返回的三元组中不能出现相同的三元组,因此需要对输入的list进行排序。只需要保证:

  • 第二重循环枚举到的元素不小于当前第一重循环枚举到的元素;
  • 第三重循环枚举到的元素不小于当前第二重循环枚举到的元素。

这样做的目的是让结果中的元组按数的大小进行排列,这样就可以避免出现重复的结果。同时,对于每一重循环而言,相邻两次枚举的元素不能相同,否则也会造成重复。再进行一定的思考可以发现如果固定第一重循环的数x和第二重循环的数y,第三重循环进行遍历时就只有唯一的数z满足等式。当第二重循环进行下一次遍历,y'>y,所以c'需要小于c,即c'一定出现在c的左侧。所以可以从小到大枚举b,从大到小枚举c。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
#官方题解
class Solution:
def threeSum(self, nums: List[int]) -> List[List[int]]:
n = len(nums)
nums.sort()
ans = list()

# 枚举 a
for first in range(n):
# 需要和上一次枚举的数不相同
if first > 0 and nums[first] == nums[first - 1]:
continue
# c 对应的指针初始指向数组的最右端
third = n - 1
target = -nums[first]
# 枚举 b
for second in range(first + 1, n):
# 需要和上一次枚举的数不相同
if second > first + 1 and nums[second] == nums[second - 1]:
continue
# 需要保证 b 的指针在 c 的指针的左侧
while second < third and nums[second] + nums[third] > target:
third -= 1
# 如果指针重合,随着 b 后续的增加
# 就不会有满足 a+b+c=0 并且 b<c 的 c 了,可以退出循环
if second == third:
break
if nums[second] + nums[third] == target:
ans.append([nums[first], nums[second], nums[third]])

return ans

三数之和
http://example.com/2024/02/14/三数之和/
作者
Z Z
发布于
2024年2月14日
许可协议