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 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87
| #include <iostream> #include <vector> #include <algorithm> using namespace std;
class Solution { public: vector<vector<int>> threeSum(vector<int> &nums) { vector<vector<int>> res; if (nums.size() < 3) return res; vector<int> jie = {0, 0, 0};
sort(nums.begin(), nums.end());
int n = nums.size(); int i; int i_value = INT_MAX; for (i = 0; i <= n - 1; i++) { while (nums.at(i) == i_value) { i++; if (i >= n - 2) return res; } int j = i + 1; int k = n - 1; int j_value = INT_MAX; int k_value = INT_MAX; while (j < k) { int flag = 0; while (nums.at(j) == j_value) { j++; if (j >= k)
{ flag = 1; break; } } if (flag) break; while (nums.at(k) == k_value) { k--; if (j >= k) { flag = 1; break; } } if (flag) break; int sum = nums.at(i) + nums.at(j) + nums.at(k); if (sum == 0) { i_value = nums.at(i); j_value = nums.at(j); k_value = nums.at(k); jie.at(0) = i_value; jie.at(1) = j_value; jie.at(2) = k_value; res.push_back(jie); j++; k--; } else if (sum < 0) { j++; } else { k--; } } } return res; } };
|