leetcode15 3Sum

Posted yawenw

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了leetcode15 3Sum相关的知识,希望对你有一定的参考价值。

 1 """
 2 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.
 3 Note:
 4 The solution set must not contain duplicate triplets.
 5 Example:
 6 Given array nums = [-1, 0, 1, 2, -1, -4],
 7 A solution set is:
 8 [
 9   [-1, 0, 1],
10   [-1, -1, 2]
11 ]
12 """
13 """
14 two Sum用了hash。而Three Sum不需要用
15 先对数组排序
16 然后用三个指针 i, l, r 来进行遍历
17 先确定一个i的值,将i指向第一个不重复的值,l 指向头,r指向尾
18 第二层循环 while l<r
19 如果和大于0, r左移
20 如果和小于0, l右移
21 如果和等于0,保存结果
22 将l,r分别移到不重复这个值的位置
23 l,r再同时左移和右移
24 """
25 class Solution:
26     def threeSum(self, nums):
27         res = []
28         nums.sort()
29         for i in range(len(nums) -2):
30             if i > 0 and nums[i] == nums[i-1]:
31                 continue
32             l, r = i+1, len(nums)-1
33             while l < r:
34                 if nums[i] + nums[l] + nums[r] > 0:
35                     r -= 1
36                 elif nums[i] + nums[l] + nums[r] < 0:
37                     l += 1
38                 else:
39                     res.append([nums[i], nums[l], nums[r]])
40                     while l < r and nums[l] == nums[l+1]:
41                         l += 1
42                     while l < r and nums[r] == nums[r-1]:
43                         r -= 1
44                     l += 1
45                     r -= 1
46         return res

 

以上是关于leetcode15 3Sum的主要内容,如果未能解决你的问题,请参考以下文章

leetcode 15 3Sum

[leetcode][15] 3Sum

Leetcode 15. 3Sum(python)

Leetcode 15. 3Sum

leetcode15 3Sum

[leetcode]15. 3Sum[UNSOLVED]