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

 

posted @ 2020-02-20 11:44  yawenw  阅读(144)  评论(0编辑  收藏  举报