我正在研究2和问题,在那里我搜索t-x(或y)来查找x + y = t以及是否有一个值添加到x使得总和在t中。
T是从-10000
到10000
的所有值。我实现了nlogn
解决方案,因为我不知道如何使用哈希表(我看到的大多数示例都是字符而不是整数)。我的nlogn
解决方案是使用快速排序对数字进行排序,然后使用二进制搜索来搜索t-x
。
我相信我的问题是目前我也在输入重复项。例如,在数组{1,2,3,4,5}中,如果t为5,2 + 3和1 + 4等于5,但它应该只给出一个,而不是两个。换句话说,我需要得到所有" distinct"或者不同的总和。我相信我的代码出了问题。据说x!= y这条线应该让它与众不同,虽然我不明白怎样,甚至在实施时仍然给出了错误的答案。
以下是包含测试用例的数据文件的链接: http://bit.ly/1JcLojP 100的答案是42,1000是486,10000是496,1000000是519.我的输出是84,961,1009,我没有测试100万。
对于我的代码,您可以假设二进制搜索和快速排序已正确实现。快速排序本来应该给你多少次比较事情,但我从来没有弄清楚如何返回两件事(比较和索引)。
#include <stdio.h>
#include <stdlib.h>
#include <iostream>
#include <fstream>
#include <string>
#include <ctime>
#include <cstdlib>
#include <cmath>
#include <cctype>
using namespace std;
long long binary_search(long long array[],long long first,long long last, long long search_key)
{
long long index;
if (first > last)
index = -1;
else
{
long long mid = (first + last)/2;
if (search_key == array[mid])
index = mid;
else
if (search_key < array[mid])
index = binary_search(array,first, mid-1, search_key);
else
index = binary_search(array, mid+1, last, search_key);
} // end if
return index;
}// end binarySearch
long long partition(long long arr[],long long l, long long h)
{
long long i;
long long p;
long long firsthigh;
p = h;
firsthigh = l;
long long temporary = 0;
for (i=(l +0); i<= h; i++)
{
if (arr[i] < arr[p])
{
long long temp2 = 0;
temp2 = arr[i];
arr[i] = arr[firsthigh];
arr[firsthigh] = temp2;
firsthigh ++;
}
}
temporary = arr[p];
arr[p] = arr[firsthigh];
arr[firsthigh] = temporary;
return(firsthigh);
}
long long quicksort(long long arr[], long long l, long long h)
{
long long p; /* index of partition */
if ((h-l)>0)
{
p = partition(arr,l,h);
quicksort(arr,l,p-1);
quicksort(arr,p+1,h);
}
if(h == l)
return 1;
else
return 0;
}
int main(int argc, const char * argv[])
{
long long array[1000000] = {0};
long long t;
long long count = 0;
ifstream inData;
inData.open("/Users/SeanYeh/downloads/100.txt");
cout<<"part 1"<<endl;
for (long long i=0;i<100;i++)
{
inData >> array[i];
//cout<<array[i]<<endl;
}inData.close();
cout<<"part 2"<<endl;
quicksort(array,0,100);
cout<<"part 3"<<endl;
for(t = 10000;t >= -10000;t--)
{
for(int x = 0;x<100;x++)
{
long long exists = binary_search(array,0,100,t-array[x]);
if (exists >= 0)
{
count++;
}
}
}
cout<<"The value of count is: "<<count<<endl;
}
答案 0 :(得分:1)
如果您不想返回重复值请不要继续从列表的开头搜索。
示例:
list = {1,2,3,4,5}
total = 5
{2,3,4,5}
)
{3,4,5}
如果您有重复的项目,则会出现问题,因此列表
{1,1,2,3,4,5} or {1,1,1,2,3,4,5}
即使使用我已经显示的方法,这也会产生2个结果,如果这是可以接受的,则忽略此答案的下一部分,否则您可以使用 std::set 强>
当你拿到列表时,你把它放在一个集合中。该集将自动消除重复项,然后您可以继续使用上面显示的方法。
注意: std :: set在内部实现为二叉搜索树,因此您也可以摆脱快速排序和二进制搜索实现,因为std::set
同时执行
答案 1 :(得分:1)
为避免重复,您需要将二进制搜索范围从[0,n]
更改为[x+1,n]
。一旦你发现存在一个总和就会突破循环。
long long exists=binary_search(array, x+1, 100, t-array[x]);
if(exists >= 0)
{
count++;
break;
}