请给出一个运行时间为O(nlgn)的算法,使之能在给定一个由n个整数构成的集合里快速判断是否存在两个元素,其和等于某一指定值key。
方法一:
思路:
1.对数组进行归并排序或快速排序,运行时间为O(nlgn);
2.对已经排序的的数组进行遍历,并在遍历当前元素x时,在其后的序列里用binary search查找是否存在key-x,。binary search 运行时间为O(lgn),所以该步的的总运行时间为O(nlgn).
分析:该算法总的运行时间为O(nlgn)。
代码示例:
/*binary search: recursive edition
the input array is acsen-sorted array
the output is the index (starting from 0) of the array if found, or -1 if not found.
the total time is O(lgn)
*/
template<typename T>
int BinarySearch(T arr[], int first,int last,const T key)
{
if(first>last) return -1;
if(first==last)
{
if(key==arr[first])
return first;
else
return -1;
}
int mid=(first+last)/2;
if(key==arr[mid]) return mid;
else if(key<arr[mid])
{
return BinarySearch(arr,first,mid-1,key);
}
else
{
return BinarySearch(arr,mid+1,last,key);
}