又做了一些
This commit is contained in:
60
threeSum.cpp
60
threeSum.cpp
@@ -7,25 +7,57 @@ using namespace std;
|
||||
class Solution
|
||||
{
|
||||
public:
|
||||
vector<vector<int>> threeSum(vector<int> &nums)
|
||||
vector<vector<int>> threeSum(std::vector<int> &nums)
|
||||
{
|
||||
vector<int> zeros, positives, negatives;
|
||||
set<vector<int>> result;
|
||||
|
||||
sort(nums.begin(), nums.end());
|
||||
set<vector<int>> res;
|
||||
// 划分元素
|
||||
for (int num : nums) {
|
||||
if (num == 0) {
|
||||
zeros.push_back(num);
|
||||
} else if (num > 0) {
|
||||
positives.push_back(num);
|
||||
} else {
|
||||
negatives.push_back(num);
|
||||
}
|
||||
}
|
||||
|
||||
for(int i = 0; i < nums.size(); i++) {
|
||||
for(int j = i + 1; j < nums.size(); j++) {
|
||||
for(int k = nums.size() - 1; k > j ; k--) {
|
||||
if(nums[i] + nums[j] + nums[k] == 0) {
|
||||
vector<int> tmp = {nums[i], nums[j], nums[k]};
|
||||
res.insert(tmp);
|
||||
}
|
||||
|
||||
// 排序正数和负数
|
||||
std::sort(positives.begin(), positives.end());
|
||||
std::sort(negatives.begin(), negatives.end());
|
||||
|
||||
if (zeros.size() != 0) {
|
||||
if (zeros.size() >= 3) {
|
||||
result.insert({0, 0, 0});
|
||||
}
|
||||
for (int positive : positives) {
|
||||
if (std::binary_search(negatives.begin(), negatives.end(), -positive)) {
|
||||
result.insert({-positive, 0, positive});
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return vector<vector<int>>(res.begin(), res.end());
|
||||
//正正负
|
||||
for(int i = 0; i < positives.size(); i++) {
|
||||
for(int j = i + 1; j < positives.size(); j++) {
|
||||
if(std::binary_search(negatives.begin(), negatives.end(), -(positives[i] + positives[j]))){
|
||||
result.insert({-(positives[i] + positives[j]), positives[i], positives[j]});
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
//负负正
|
||||
for(int i = 0; i < negatives.size(); i++) {
|
||||
for(int j = i + 1; j < negatives.size(); j++) {
|
||||
if (std::binary_search(positives.begin(), positives.end(), -(negatives[i] + negatives[j]))) {
|
||||
result.insert({negatives[i], negatives[j], -(negatives[i] + negatives[j])});
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
return vector<vector<int>>(result.begin(), result.end());
|
||||
}
|
||||
};
|
||||
|
||||
@@ -34,8 +66,8 @@ int main()
|
||||
Solution s;
|
||||
vector<int> nums = {-1, 0, 1, 2, -1, -4};
|
||||
vector<vector<int>> res = s.threeSum(nums);
|
||||
for(auto &v : res) {
|
||||
for(auto &i : v) {
|
||||
for (auto &v : res) {
|
||||
for (auto &i : v) {
|
||||
cout << i << " ";
|
||||
}
|
||||
cout << endl;
|
||||
|
Reference in New Issue
Block a user