【发布时间】:2016-12-22 15:20:42
【问题描述】:
问题陈述如下:
这个问题的目标是实现 2-SUM 算法的一个变体。
该文件包含一百万个整数,包括正数和负数(可能有一些重复!)。这是您的整数数组,文件的第 i 行指定数组的第 i 个条目。
您的任务是计算区间 [-10000,10000](含)内的目标值 t 的数量,使得输入文件中存在满足 x+y=t 的不同数字 x,y。
写出你的数字答案(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的范围吗?如果它们
标签: arrays sorting hashtable unordered-set