码迷,mamicode.com
首页 > 其他好文 > 详细

[LC] 15. 3Sum

时间:2019-10-11 10:31:45      阅读:91      评论:0      收藏:0      [点我收藏+]

标签:cat   list   let   lis   nbsp   +=   append   and   div   

Given an array nums of n integers, are there elements abc in nums such that a + b + c = 0? Find all unique triplets in the array which gives the sum of zero.

Note:

The solution set must not contain duplicate triplets.

Example:

Given array nums = [-1, 0, 1, 2, -1, -4],

A solution set is:
[
  [-1, 0, 1],
  [-1, -1, 2]
]

Time: O(N^2)
 1 class Solution:
 2     def threeSum(self, nums: List[int]) -> List[List[int]]:
 3         res = []
 4         if nums is None:
 5             return res
 6         
 7         nums.sort()
 8         for i in range(len(nums) - 2):
 9             if i > 0 and nums[i] == nums[i - 1]:
10                 continue
11             target = -nums[i]
12             left = i + 1
13             right = len(nums) - 1
14             while left < right:
15                 if nums[left] + nums[right] == target:
16                     lst = [nums[i], nums[left], nums[right]]
17                     res.append(lst)
18                     left += 1
19                     right -= 1
20                     while left < right and nums[left] == nums[left - 1]:
21                         left += 1
22                     while left < right and nums[right] == nums[right + 1]:
23                         right -= 1
24                 elif nums[left] + nums[right] < target:
25                     left += 1
26                 else:
27                     right -= 1
28         return res
29         

 

[LC] 15. 3Sum

标签:cat   list   let   lis   nbsp   +=   append   and   div   

原文地址:https://www.cnblogs.com/xuanlu/p/11652420.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!