c++ - C++如何优化这个算法?(标准::地图)
问题描述
问题如下:给定一个数字's',s ∈ [0, 10^6],和一个数字'n',n ∈ [0, 50000],然后是n个数字,我们必须找出如何许多数字对的总和等于“s”数(我们必须使用映射或集合来解决它)
这是示例:
输入:
5 (this is s)
6 (this is n)
1
4
3
6
-1
5
输出:
2
解释:这些是 (1,4) 和 (6,−1) 对。(1 +4 = 5 和 6 + (-1) = 5)
这是我的“解决方案”,我什至不知道它是否正确,但它适用于我们得到的示例。
#include <iostream>
#include <map>
#include <iterator>
using namespace std;
int main()
{
cin.tie(0);
ios::sync_with_stdio(false);
int s;
cin >> s;
int n;
cin >> n;
map<int, int> numbers;
int element;
int counter = 0;
for(int i=0; i<n;i++)
{
cin >> element;
numbers.insert(pair<int, int>(element, s-element));
}
for(map<int, int>::iterator it = numbers.begin(); it != numbers.end(); it++)
{
map<int, int>::iterator it2 = it;
while(it2 != numbers.end())
{
if(it->second == it2->first)
{
counter++;
break;
}
it2++;
}
}
cout << counter << "\n";
return 0;
}
感谢您提前回答!我仍然是初学者,我正在学习,对不起。
解决方案
element, s-element
是个好主意,但没有理由存储所有对,然后才检查重复项。这将删除O(n^2)
您最后的循环。
使用散列的标准方法是:
seen=unordered_map<number,count>()
for 1...n:
e = read_int()
if (s-e) in seen:
duplicates+=seen[s-e] # Found new seen[s-e] duplicates.
if e in seen:
seen[e]+=1
else:
seen.insert(e,1)
return duplicates
推荐阅读
- ruby - 用 ruby 转义 Postgresql hstore 类型?
- python - Python数据存储方法
- docker - 如何在 Dockerfile 中提取 Docker 映像?
- angular - Jasmine 单元测试,ActivatedRoute 上的 .subscribe 问题
- php - 在PHP中获取python程序的运行状态
- c# - 播种 ServiceStack 数据库
- serial-port - 提示硬线返回 fcntl:无效参数
- scala - 将scala列表转换为数组
- mesos - 在 Aurora 和 Mesos 上部署 Heron 调度程序文件时如何找到它?
- python - Pythoncom - 如何收听 Outlook 传出消息?