的各种版本2和算法的问题说明如下:射程资金
这个问题的目标是实现2和算法的变体。
该文件包含100万个整数,包括正数和负数(可能有一些重复!)。这是整数数组,其中第i行指定数组的第i个条目。
您的任务是计算区间[-10000,10000](含)内的目标值数t,以使输入文件中有不同数x,y满足x + y = t。
编写数字答案(0到20001之间的整数)。
我实现了一个天真的解决方案:
#include <iostream>
#include <fstream>
#include <unordered_set>
#include <vector>
#include <algorithm>
#define FILE "2sum.txt"
#define LEFT -10000
#define RIGHT 10000
using namespace std;
class cal_2sum{
int count;
unordered_set<long> hashT;
vector<long> array;
public:
cal_2sum(){
count = 0;
}
int getCount(){
return this->count;
}
int calculate(string filename,int left, int right){
ifstream file(filename);
long num;
while(file>>num){
hashT.insert(num);
}
for(auto it = hashT.begin(); it != hashT.end(); ++it)
array.push_back(*it);
sort(array.begin(),array.end());
for(long target = left; target<=right; target++){
bool found = false;
for(auto it = array.begin(); it != array.end(); ++it){
long otherHalf = target - (*it);
auto verdict = hashT.find(otherHalf);
if(verdict != hashT.end() && (*verdict) != (*it)){
found = true;
break;
}
}
if(found == true)
count++;
cout<<count<<endl;
}
}
};
int main(){
cal_2sum res;
res.calculate(FILE,LEFT,RIGHT);
cout<<res.getCount()<<endl;
return 0;
}
它给出了正确的答案,但是,实在是太慢了。我如何改进解决方案。 输入数字在[-99999887310 ,99999662302]范围内。
您是否对整数x和y的范围有任何了解?如果它们<= 10^7,就可以像计数排序那样将值存储在一个数组中,比如说arr [3] = 2意味着有2个值的值为3.这将显着加快hashT.find )有平均情况O(1),而不是最坏情况O(1).. –