三数之和
给你一个包含n个整数的数组nums,判断nums中是否存在三个元素a,b,c,使得a + b + c = 0?请你找出所有和为0且不重复的三元组。
注意:答案中不可以包含重复的三元组。
示例 1:
输入:nums = [-1,0,1,2,-1,-4]
输出:[[-1,-1,2],[-1,0,1]]
示例 2:
输入:nums = []
输出:[]
示例 3:
输入:nums = [0]
输出:[]
提示:
- 0 <= nums.length <= 3000
- -105 <= nums[i] <= 105
Solution
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65
| #include <iostream> #include <vector> #include <algorithm> using namespace std;
class Solution { public: vector<vector<int>> threeSum(vector<int>& nums) { vector<vector<int>> results; if (nums.size() < 3) { return results; } sort(nums.begin(), nums.end()); int len = nums.size(); for (int i = 0; i < len - 2; ++i) { if (i > 0 && nums[i] == nums[i - 1]) { continue; } if (nums[i] + nums[i + 1] + nums[i + 2] > 0) { break; } if (nums[i] + nums[len - 2] + nums[len - 1] < 0) { continue; } int left = i + 1; int right = len - 1; while (left < right) { int sum = nums[i] + nums[left] + nums[right]; if (sum < 0) { left++; } else if ( sum > 0) { right--; } else { vector<int> result = {nums[i], nums[left], nums[right]}; results.emplace_back(result); while (left < right && nums[left] == nums[left + 1]) { left++; } left++; while (left < right && nums[right - 1] == nums[right]) { right--; } right--; } } } return results; } };
int main() { vector<int> input; vector<vector<int>> results;
input = {-1,0,1,2,-1,-4}; results = Solution().threeSum(input); for (int i = 0; i < results.size(); ++i) { for (int j = 0; j < results[i].size(); ++j) { std::cout << results[i][j] << " "; } std::cout << std::endl; } }
|