The file contains 1 million integers, both positive and negative (there might be some repetitions!).This is your array of integers, with the
ith
row of the file specifying the
ith
entry of the array.
Your task is to compute the number of target values
t
in the interval [-10000,10000] (inclusive) such that there are distinct numbers
x,y
in the input file that satisfy
x+y=t
. (NOTE: ensuring distinctness requires a one-line addition to the algorithm from lecture.)
Write your numeric answer (an integer between 0 and 20001) in the space provided.
OPTIONAL CHALLENGE: If this problem is too easy for you, try implementing your own hash table for it. For example, you could compare performance under the chaining and open addressing approaches to resolving collisions.
这个不知道怎么用Hash实现,只采用了一种简单的实现:
// Reference: http://tech-wonderland.net/blog/summary-of-ksum-problems.html
#include <iostream>
#include <fstream>
#include <math.h>
#include <vector>
#include <sstream>
#include <set>
using namespace std;
bool Sum2(set<__int64> &inputs, int target)
{
set<__int64>::iterator itBeg;
set<__int64>::iterator itEnd;
itBeg = inputs.begin();
itEnd = inputs.end();
itEnd--;
__int64 sum;
bool result = false;
while(itBeg != itEnd)
{
sum = *itBeg + *itEnd;
if (sum == target)
{
result = true;
break;
}
else if (sum < target)
{
itBeg++;
}else{
itEnd--;
}
}
return result;
}
int main()
{
ifstream infile;
infile.open("algo1-programming_prob-2sum.txt");
set<__int64> inputSet;
__int64 input;
while(!infile.eof())
{
infile >> input;
inputSet.insert(input);
}
int sum =0;
for (int i=-10000; i<10001; i++)
{
if (Sum2(inputSet, i))
{
sum++;
}
}
cout << "The number is " << sum << endl;
infile.close();
return 0;
}
参考:
[1] Summary for leetcode 2Sum, 3Sum, 4Sum, K Sum http://tech-wonderland.net/blog/summary-of-ksum-problems.html