您的位置:首页 > 其它

15. 3Sum

2016-03-23 20:31 351 查看
题目

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

Note:

Elements in a triplet (a,b,c) must be in non-descending order. (ie, a ≤ b ≤ c)
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)


思路:排序后两端夹挤。

注意:避免添加重复triplet. 

改进:跳过相邻重复数。 

复杂度: O(n^2)。

Java:

public ArrayList<ArrayList<Integer>> threeSum(int[] num) {
Arrays.sort(num);
ArrayList<ArrayList<Integer>> result = new ArrayList<ArrayList<Integer>>();
if(num.length<3) return result;
for(int i=0;i<num.length-2;){
int b = i+1, e = num.length-1;
while(b<e){
if(num[b]+num[e]+num[i]==0) {
ArrayList <Integer> temp = new ArrayList <Integer>();
temp.add(num[i]);temp.add(num[b]);temp.add(num[e]);
if(!result.contains(temp))
result.add(temp);
b++;e--;
while(b<(num.length-1) && num[b-1]==num[b]) b++;
while(e>1 && num[e+1]==num[e]) e--;
}
else if(num[b]+num[e]+num[i]<0)
b++;
else
e--;
}
i++;
while(i<(num.length-2) && num[i-1]==num[i]) i++;
}
return result;


Python:

class Solution(object):
def threeSum(self, nums):
"""
:type nums: List[int]
:rtype: List[List[int]]
"""
sorted_nums = sorted(nums)
l = len(nums)
result = []
for k in xrange(l-2):
i,j = k+1,l-1
target = 0-sorted_nums[k]
while i<j:
if sorted_nums[i] + sorted_nums[j] == target:
temp = [sorted_nums[k], sorted_nums[i], sorted_nums[j]]
if temp not in result:
result.append(temp)
if sorted_nums[i] == sorted_nums[i+1]:
i+=1
elif sorted_nums[j] == sorted_nums[j-1]:
j-=1
else:
i+=1;j-=1
elif sorted_nums[i] + sorted_nums[j] < target:
i+=1
else:
j-=1
return result
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  Leetcode NSum