请给出一个运行时间为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);
}

本文介绍了两种O(nlgn)时间复杂度的算法,用于在一个整数数组中判断是否存在两个元素之和等于指定值key。方法一通过归并排序或快速排序后使用二分查找;方法二则是排序后创建互补数组并进行归并操作,检查是否有相邻相等元素。详细代码实现和分析包含在内。
最低0.47元/天 解锁文章
6886

被折叠的 条评论
为什么被折叠?



