微软等数据结构+算法面试100题(39)-- 左旋数组中查找

一个数组是由一个递减数列左移若干位形成的,比如{4,3,2,1,6,5}
是由{6,5,4,3,2,1}左移两位形成的,在这种数组中查找某一个数。

 

//递减数组左旋可以分为俩种情况。|| 表示分界处
/*
第一种:6,5,4,3,2,1,||   9,8,7
第二种:3,2,1,||  9,8,7,6,5,4
数组[low....high]。mid=low+(high-low)/2;
如果是p[mid]<=p[low]。那么就是第一种。[low,mid]是有序的。[mid,high]不是有序的。
如果是p[mid]>p[low]。那么就是第而种。[low,mid]是无序的。[mid,high]是有序的。
每一种情况再分要找的元素n和p[mid]的关系。看n是在前半段还是后半段。这样类似于二分查找的思想。
*/
int RotateLeftFindRecursion(int *p,int low,int high,int n)
{
	if(low>high)
		return -1;
	if(low==high)
		return p[low]==n?low:-1;

	int mid=low+(high-low)/2;
	if(p[mid]<=p[low])
	{
		if(n>=p[mid]&&n<=p[low])
			return RotateLeftFindRecursion(p, low,mid,n);
		else
			return RotateLeftFindRecursion(p, mid+1,high,n);
	}
	else
	{
		if(n<=p[mid]&&n>=p[high])
			return RotateLeftFindRecursion(p, mid,high,n);
		else
			return RotateLeftFindRecursion(p, low,mid-1,n);
	}
}

void RotateLeftFindTest()
{
	int p[]={4,3,2,1,10,9,8,7,6,5};
	int len=sizeof(p)/sizeof(int);
	cout<<"array : ";
	ShowArray(p,len);
	int n=0;
	while(1)
	{
		cout<<"n : ";
		cin>>n;
		int index=RotateLeftFind(p,0,len-1,n);
		int index1=RotateLeftFindRecursion(p,0,len-1,n);
		cout<<"index : "<<index<<endl;
		cout<<"p[index] : "<<p[index]<<endl;
		cout<<"index1 : "<<index1<<endl;
		cout<<"p[index1] : "<<p[index1]<<endl;
	}
}


 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值