您的位置:首页 > 其它

算法导论 练习题 2.3-7

2012-04-12 11:08 232 查看
[淘宝笔试题,哪年出的题不记得了]

请给出一个运行时间为O(nlgn)的算法,使之能在给定一个由n个整数构成的集合S和另一个整数x时,判断出S中是否存在有两个其和等于x的元素?

1、先对数组排序,然后利用折半查找实现。

#include <iostream>
using namespace std;

void sort(int a[],int size)
{
// 直接插入排序
int key =0;
for(int i=1;i<size;++i)
{
key = a[i];
int j;
for(j=i-1;j>=0;--j)
{
if(a[j] > a[key])
a[j+1] = a[j];
else
break;
}
a[j+1] = key;
}
}
bool b_query(int a[],int size,int _x)
{
int low = 0;
int high = size-1;
int key = _x;
while(low <= high)
{
int mid = (low+high)/2;
if(a[mid] == key) return true;
if(a[mid] < key)
low = mid + 1;
else if(a[mid] > key)
high = mid - 1;
}
return false;
}
bool query_x(int a[],int size,int x)
{
sort(a,size);
for(int i=0;i<size;++i)
{
if(true == b_query(a,size,x-a[i]))
return true;
}
return false;
}
void main()
{
int a[] = {-10,10,5,9,-90,30,8,7,4,3};
int x;
cin >> x;
if(true == query_x(a,10,x))
cout << " 找到" <<endl;
else
cout << "未找到" << endl;

}


2、利用hash_set实现

#include <iostream>
#include <hash_set>   // 注意要使用hash_set时,需要关联的头文件的格式
#include <algorithm>
using namespace std;
using namespace stdext;  // 注意要使用hash_set时,需要关联的命名空间格式

bool query_x(int a[],int size,int x)
{
hash_set<int> haset;
for(int i=0;i<size;++i)
haset.insert(haset.end(),a[i]);
for(int i=0;i<size;++i)
{
hash_set<int>::iterator ip;
ip = find(haset.begin(),haset.end(),x-a[i]); // 时间复杂度是O(1)
if(ip != haset.end())
return true;
}
return false;
}
void main()
{
int a[] = {-10,10,5,9,-90,30,8,7,4,3};
int x;
cin >> x;
if(true == query_x(a,10,x))
cout << " 找到" <<endl;
else
cout << "未找到" << endl;

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: