题目:
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)题解:
思路是对每一个数a in (0,size-1),求-a的two sum。
如果用set去重复,可以通过时间限制,但two sum的时候如果用map的方式则无法通过。
C++版:
class Solution {
public:
vector<vector<int> > threeSum(vector<int> &num) {
sort(num.begin(), num.end());
vector<vector<int>> results;
for(int i = 0; i < num.size(); i++) {
if(i > 0 && num[i] == num[i-1])
continue;
twoSum(num, i, results);
}
return results;
}
void twoSum(vector<int> &num, int index, vector<vector<int>> &temp) {
if(index >= num.size()-2)
return;
int begin = index+1, end = num.size()-1;
while(begin < end) {
if(num[begin] + num[end] + num[index] == 0) {
vector<int> a;
a.push_back(num[index]);
a.push_back(num[begin]);
a.push_back(num[end]);
temp.push_back(a);
begin++;
while(begin < end && a[1] == num[begin])
begin++;
end--;
while(end > begin && a[2] == num[end])
end--;
} else if(num[begin] + num[end] + num[index] < 0) {
begin++;
} else {
end--;
}
}
}
};
Java版:
public class Solution {
public List<List<Integer>> threeSum(int[] num) {
List<List<Integer>> res = new ArrayList<List<Integer>>();
if(num.length < 2)
return res;
Arrays.sort(num);
for(int i = 0; i < num.length; i++) {
if(i > 0 && num[i] == num[i-1])
continue;
int begin = i+1, end = num.length-1;
while(begin < end) {
if(num[begin] + num[end] + num[i] == 0) {
List<Integer> temp = new ArrayList<Integer>();
temp.add(num[i]);
temp.add(num[begin]);
temp.add(num[end]);
res.add(temp);
begin += 1;
end -= 1;
while(begin < end && num[begin] == temp.get(1))
begin += 1;
while(begin < end && num[end] == temp.get(2))
end -= 1;
} else if(num[begin] + num[end] + num[i] < 0) {
begin += 1;
} else {
end -= 1;
}
}
}
return res;
}
}
Python版:
class Solution:
# @return a list of lists of length 3, [[val1,val2,val3]]
def threeSum(self, num):
l = []
if len(num) < 3:
return l
list.sort(num)
for i in range(0, len(num)):
if i > 0 and num[i-1] == num[i]:
continue
begin = i + 1
end = len(num)-1
while begin < end:
if num[i] + num[begin] + num[end] == 0:
temp = [num[i], num[begin], num[end]]
l.append(temp)
begin += 1
end -= 1
while begin < end and num[begin] == temp[1]:
begin += 1
while begin < end and num[end] == temp[2]:
end -= 1
elif num[i] + num[begin] + num[end] < 0:
begin += 1
else:
end -= 1
return l