二分查找法及判断一个数组中是否有两个元素之和为指定值

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

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

请给出一个运行时间为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);
	}
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值