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

LeetCode15.3 Sum

时间:2018-06-09 15:31:37      阅读:155      评论:0      收藏:0      [点我收藏+]

标签:and   层遍历   数组   题目   let   数组排序   时间复杂度   方式   nta   

题目:

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]
]

思路:

因为给的数据中可能有重复元素,想到将数组排序,以方便跳过重复元素。基于排序的元组,可以选定一个目标值,再用两端逼近的方式来求出和为目标值的两个元素。整个算法的时间复杂度为O(n^2)。

解题代码如下:

 1 class Solution(object):
 2     def threeSum(self, nums):
 3         nums.sort()
 4         res = []
 5         for i in range(len(nums) - 2):
 6             if i == 0 or (i > 0 and nums[i] != nums[i - 1]):
 7                 target = 0 - nums[i]
 8                 lo, hi = i + 1, len(nums) - 1
 9                 while lo < hi:
10                     if nums[lo] + nums[hi] == target:
11                         res.append([nums[i], nums[lo], nums[hi]])
12                         while lo < hi and nums[lo] == nums[lo + 1]:
13                             lo += 1
14                         while lo < hi and nums[hi] == nums[hi - 1]:
15                             hi -= 1
16                         lo, hi = lo + 1, hi - 1
17                     elif nums[lo] + nums[hi] > target:
18                         hi -= 1
19                     else:
20                         lo += 1
21         return res

为避免结果中出现冗余值,有两点需要注意:

一个是外层遍历选取target值是,应保证当前元素和之前一个元素不相等(见第6行)

一个是内层循环中找到一组符合条件的值后,应调整两个指针的位置,跳开重复元素(见第12、13行)

LeetCode15.3 Sum

标签:and   层遍历   数组   题目   let   数组排序   时间复杂度   方式   nta   

原文地址:https://www.cnblogs.com/plank/p/9159421.html

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