LeetCode15.3 Sum

题目:

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行)

posted @ 2018-06-09 14:23  板弓子  阅读(142)  评论(0编辑  收藏  举报