[LeetCode]15. 3Sum

来源:互联网 发布:淘宝 一件代发 编辑:程序博客网 时间:2024/06/01 10:00

Description:

Given an array S of n integers, are there elements abc in S 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.

For example, given array S = [-1, 0, 1, 2, -1, -4],A solution set is:[  [-1, 0, 1],  [-1, -1, 2]]

——————————————————————————————————————————————————————————————————————————

Solution:

看到这种题目很容易想到暴力算法(三重循环),但是用脚想也知道肯定TLE。思考许久无果,看了看Discuss,发现这类题目都算作是K Sum问题(有兴趣可以自行搜索)。

类似Container with most water的思路:

1.对输入数组nums先排好序

2.从小到大每次固定一个数 i,在剩下的数组元素中设立left标记和right标记

3.若left<right,判断nums[left]+nums[right]+nums[i]与0的关系,否则返回2

4.若相等则推入vector,并令left++,right--(注意:最后还要判断nums[left]和nums[left-1]是否相同,若相同需要再令left++,以消除重复结果,right同理),返回3

5.若<0则说明nums[left]太小(而不是nums[right]太小,因为right不能向大方向移,而是两边向中间靠拢),令left++,返回3

6.若>0则说明nums[right]太大(同理),令right--,返回3



时间复杂度:O(n^2)