LeetCode15. 3Sum
题目:
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] ]
题目分析:
先给数组排序,然后固定头部,然后还是一个2Sum的问题,但是不一样的是,这个数组是排序的,所以可以根据和target的大小不同来控制begin,end的不同。
if (nums[i] + nums[begin] + nums[end] < 0) {
begin++;
}
else if (nums[i] + nums[begin] + nums[end] > 0) {
end--;
}
else if (nums[i] + nums[begin] + nums[end] == 0) { tmp.push_back(nums[i]); tmp.push_back(nums[begin]); tmp.push_back(nums[end]); kset.insert(tmp); tmp.clear(); begin++; }
代码:class Solution { public: vector<vector<int>> threeSum(vector<int>& nums) { vector<vector<int>> res; set<vector<int>> kset; vector<int> tmp; if (nums.empty()||nums.size()<3) return res; sort(nums.begin(), nums.end()); int begin, end; for (int i = 0; i < nums.size()-2; i++) { begin = i + 1, end = nums.size() - 1; while (begin < end) { if (nums[i] + nums[begin] + nums[end] < 0) { begin++; } else if (nums[i] + nums[begin] + nums[end] > 0) { end--; } else if (nums[i] + nums[begin] + nums[end] == 0) { tmp.push_back(nums[i]); tmp.push_back(nums[begin]); tmp.push_back(nums[end]); kset.insert(tmp); tmp.clear(); begin++; } } } for (auto i : kset) res.push_back(i); return res; } };