Cracking the coding interview--Q9.3

介绍了一种在已知被旋转的有序数组中使用O(logn)复杂度进行元素搜索的算法实现,通过调整二分查找法来适应旋转数组的特点。

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

题目

原文:

Given a sorted array of n integers that has been rotated an unknown number of times, give an O(log n) algorithm that finds an element in the array. You may assume that the array was originally sorted in increasing order.
EXAMPLE:
Input: find 5 in array (15 16 19 20 25 1 3 4 5 7 10 14)
Output: 8 (the index of 5 in the array)

译文:

给一个长度为n的有序整型数组,但它已经被旋转了未知次,给一个O(log n)的算法在这个数组中找出一个元素,你可以假设这个数组的初始排列是增序的。

例如:

输入:在数组(15 16 19 20 25 1 3 4 5 7 10 14)中找出5

输出:8(5在数组中的下标为8)

解答

首先要理解这个数组是有序的,但被旋转过了,也就是说,数组部分是有序的;然后题目要求是O(log n)的算法,显然可以用到二分查找法,但数组部分有序,即前面一段有序,后面一段有序,且前面那段的数要大于等于后面那段的数(本题递增序列),所以首先需要判断a[mid]是落在前半段还是后半段假如a[mid]落在前半段(即a[mid]>=a[low]),这时如果所求值value是位于a[low]和a[mid]之间,则更新high = mid - 1;否则更新low = mid + 1。假如a[mid]落在后半段 (即a[mid]<a[low]),这时如果x的值是位于a[mid]和a[low]之间,则更新low = mid + 1;否则更新high = mid - 1,代码如下:

class Q9_3{
	public static int search(int[] a,int fromIndex,int toIndex,int value){
		int low=fromIndex;
		int high=toIndex-1;
		while(low<=high){
			int mid=(low+high)>>>1;
		/*	int midVal=a[mid];
			if(a[low]<value){
				if(midVal>value)
					high=mid-1;
				else if(midVal<)
			}*/
			if(a[mid]==value) return mid;
			if(a[mid]>=a[low]){
				if(value<a[mid]&&value>=a[low])
					high=mid-1;
				else
					low=mid+1;
			}else{
				if(value<=a[high]&&value>a[mid])
					low=mid+1;
				else
					high=mid-1;
			}
		}
		return -1;
	}
	public static void main(String[] args){
		int[] a={
        	15, 16, 19, 20, 25, 1, 3, 4, 5, 7, 10, 14
    	};
    	System.out.println(search(a,0,12,5));
	}
}

---EOF---


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值