题目
输入一个特定整数s和一组整数,要求从这组整数中找到四个数a,b,c,d,使a+b+c+d=s。按照升序排列,输出所有满足条件的a,b,c,d。具体格式如下:
输入
0
1 0 -1 0 -2 2
输出
-2 -1 1 2
-2 0 0 2
-1 0 0 1
分析
先排序,可以用hashmap缓存两个数的和,然后左右夹逼,时间复杂度O(n^2),空间复杂度O(n^2)
代码
#include <iostream>
#include <vector>
#include <unordered_map>
#include <algorithm>
using namespace std;
int main()
{
int target;
cin >> target;
int tmp;
vector<int> nums;
while (cin >> tmp)
nums.push_back(tmp);
vector<vector<int>> result;
if (nums.size() < 4)
return 0;
sort(nums.begin(), nums.end());
unordered_multimap<int, pair<int, int>> cache;
for (int i = 0; i < nums.size() - 1; ++i)
for (int j = i + 1; j < nums.size(); ++j)
cache.insert(make_pair(nums[i] + nums[j], make_pair(i, j)));
for (auto i = cache.begin(); i != cache.end(); ++i)
{
int x = target - i->first;
auto range = cache.equal_range(x);
for (auto j = range.first; j != range.second; ++j)
{
auto a = i->second.first;
auto b = i->second.second;
auto c = j->second.first;
auto d = j->second.second;
if (a != c && a != d && b != c && b != d)
{
vector<int> vec = { nums[a], nums[b], nums[c], nums[d] };
sort(vec.begin(), vec.end());
result.push_back(vec);
}
}
sort(result.begin(), result.end());
result.erase(unique(result.begin(), result.end()), result.end());
}
for (auto i = 0; i != result.size(); ++i)
{
for (auto j = 0; j != result[i].size(); ++j)
{
cout << result[i][j] << ends;
}
cout << endl;
}
}
时间: 2024-11-08 13:30:59