Problem
Question
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: 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]
]
思路
- 从头到尾遍历组合
- 给定数组先排序,然后每次二分查找,这样降低复杂度
Code
class Solution {
public:
vector<vector<int>> threeSum(vector<int>& nums) {
vector<std::vector<int>> result;
sort(nums.begin(), nums.end());
for (int i = 0; i < nums.size(); i++) {
if (binary_search(nums.begin(), nums.begin()+i, nums[i]) == false) {
for (int j = i+1; j < nums.size(); j++) {
if (binary_search(nums.begin()+i+1, nums.begin()+j, nums[j]) == false &&
binary_search(nums.begin()+j+1, nums.end(), 0-nums[i]-nums[j]) == true) {
int seq[] = {nums[i], nums[j], 0-nums[i]-nums[j]};
std::vector<int> v(seq, seq+3);
result.push_back(v);
}
}
}
}
return result;
}
};