算法导论 练习题 2.3-7
2012-04-12 11:08
232 查看
[淘宝笔试题,哪年出的题不记得了]
请给出一个运行时间为O(nlgn)的算法,使之能在给定一个由n个整数构成的集合S和另一个整数x时,判断出S中是否存在有两个其和等于x的元素?
1、先对数组排序,然后利用折半查找实现。
2、利用hash_set实现
请给出一个运行时间为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; }
相关文章推荐
- 算法导论 练习题 2.3-7
- 《算法导论》练习题2.3-7
- 算法导论 练习题 2.3-2
- 算法导论 练习题 2.3-3
- 算法导论之2.3-7练习题
- 算法导论 练习题 2.3-4
- 算法导论 练习题 2.3-6
- 算法导论 练习题 3.2-3
- 算法导论 练习题 5.3-1
- 算法导论Java实现-二分插入排序(习题2.3-6)
- 算法导论 习题2.3-4(the implemention of insertion sort recursively)
- 算法导论 练习题 9.3-6
- 算法导论 练习题 10.4-3
- 算法导论 练习题 11.2-1
- 算法导论 练习题 12.2-1
- 使用Java完成《算法导论》习题2.3-5
- 算法导论 练习题 16.2-5
- 算法导论 练习题 17.2-1
- 算法导论第15章练习题 15.4-5
- 算法导论 2.3-7