leetcode 二分查找 Search in Rotated Sorted Array

Posted clnchanpin

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了leetcode 二分查找 Search in Rotated Sorted Array相关的知识,希望对你有一定的参考价值。

Search in Rotated Sorted Array

 Total Accepted: 28132 Total Submissions: 98526My Submissions

Suppose a sorted array is rotated at some pivot unknown to you beforehand.

(i.e., 0 1 2 4 5 6 7 might become 4 5 6 7 0 1 2).

You are given a target value to search. If found in the array return its index, otherwise return -1.

You may assume no duplicate exists in the array.



题意:一个已经排序好的数组,被按某个位置旋转了一次。给定一个值target,在该旋转后的数组里查找该值。

思路:二分查找
难点在于确定往数组的哪一半段继续二分查找
设起点、中间点、终点分别为 start、middle、end (採用前闭后开的区间表示方法
假设target = A[middle] return middle
假设A[middle] >= A[start],则[start,middle)单调递增
1.假设target < A[middle] && target >= A[start],则 end = middle
2.start = middle + 1, otherwise
假设A[middle] < A[start]。则[middle,end)单调递增
1.假设target > A[middle] && target <= A[end - 1],则 start = middle + 1
2.end = middle, otherwise


复杂度:时间O(log n)。空间O(1)


int search(int A[], int n, int target){
	int start = 0, end = n, middle ;
	while(start < end){
		middle = (start + end) / 2;
		if(A[middle] == target) return middle;
		if(A[middle] >= A[start]){
			if(target >= A[start] && target < A[middle]){
				end = middle;
			}else{
				start = middle + 1;
			}
		}else{
			if(target > A[middle] && target <= A[end - 1]){
				start = middle + 1;
			}else{
				end = middle;
			}
		}
	}
	return -1;
}




















以上是关于leetcode 二分查找 Search in Rotated Sorted Array的主要内容,如果未能解决你的问题,请参考以下文章

LeetCode 1760. Minimum Limit of Balls in a Bag - 二分查找(Binary Search)系列题19

leetcode 33 Search in Rotated Sorted Array

Python 解LeetCode:33. Search in Rotated Sorted Array

leetcode 81. Search in Rotated Sorted Array II 搜索旋转排序数组 II(中等)

LeetCode35 - Search Insert Position--二分查找,若不存在则返回应插入的位置

LeetCode 33. Search in Rotated Sorted Array