题目
Given an array S of n integers, are there elements a,b,c inS 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)
思路
这是Ksum类的问题,求出数组中K个数满足和为target的值。这一类问题都有类似解法。
可以先把数组非递减排序,然后从头到尾遍历数组,每次固定一个数nums[a],然后就是从剩下的数当中找到和为-nums[a]的两个数,由于数组是有序的,可以从头尾分别往中间靠拢,这样找两个和为-nums[a]的时间复杂度为o(n)
排序的时间复杂度为O(nlgn),找出数据并去重的时间复杂度为O(n^2),整体时间复杂度为O(nlgn)+O(n^2),当n很大时时间复杂度为O(n^2)
代码
Python
class Solution(object):
def threeSum(self, nums):
"""
:type nums: List[int]
:rtype: List[List[int]]
"""
leng = len(nums)
res = []
if (nums == None or leng < 3):
return res
nums.sort()
for a in xrange(leng):
#去重
if (a > 0 and nums[a] == nums[a-1]):
continue
b = a + 1;
c = leng - 1;
while(b < c):
tsum = nums[a] + nums[b] + nums[c]
if (tsum < 0):
#头指针往前移动
b += 1
elif (tsum > 0):
#尾指针往后移动
c -= 1
else:
item = []
item.append(nums[a])
item.append(nums[b])
item.append(nums[c])
res.append(item)
#如果有相等数字,则头尾指针要移动(去重)
while(True):
b += 1
if (b < c and nums[b-1] == nums[b]):
continue
else:
break
while(True):
c -= 1
if (c > b and nums[c+1] == nums[c]):
continue
else:
break
return res
Java
public class Solution {
public List<List<Integer>> threeSum(int[] nums) {
List<List<Integer>> res = new ArrayList<List<Integer>>();
if (nums == null || nums.length < 3) return res;
//先对数组排序
Arrays.sort(nums);
int len = nums.length;
int a,b,c,sum;
for(a = 0; a < len; a++){
//去重
if(a > 0 && nums[a] == nums[a-1]) continue;
b = a + 1;
c = len - 1;
while(b < c){
sum = nums[a] + nums[b] + nums[c];
if(sum < 0) b++;//如果sum太小,头指针往后移动,找更大的数
else if(sum > 0) c--;//如果sum太大,尾指针往前移动
else{
List<Integer> item = new ArrayList<Integer>();
item.add(nums[a]);
item.add(nums[b]);
item.add(nums[c]);
res.add(item);
while((b+=1) < c && nums[b-1] == nums[b]){
continue;
}
while((c-=1) > b && nums[c+1] == nums[c]){
continue;
}
}
}
}
return res;
}
}