您的位置:首页 > 其它

033 Search in Rotated Sorted Array[Leetcode]

2015-08-03 23:55 465 查看

题目描述

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.

虽然是旋转过的,但本质上是有序的,并且分为最多两段(也可能旋转的位置就是头部,即没有元素被旋转)。如果线性查找就没有利用分段有序的特性,查找的时间为O(n)。既然是查找,不难想到使用二分法,时间复杂度可降到O(log n)。而这边的二分法需要加入对二分方向的判断。

以4567012为例,中间数字mid为7,mid > end,说明旋转后的最小值在7的右边。如果要找的target值大于4且小于7,那么在start和mid-1之间继续二分;如果要找的值比start小,那么在mid+1和end之间继续二分查找。

另一种情况是,旋转后的最小值位于mid的左边,如6701234。它的特征是mid < start。如果target值大于end,那么在start和mid-1之间继续二分;否则在mid+1和end之间继续二分。

class Solution {
public:
int search(vector<int>& nums, int target) {
return helper(0, nums.size() - 1, nums, target);
}

//Basic Binary Search with considering two added situations because of rotation.
int helper(int start, int end, const vector<int> &A, int target){
int mid=(start+end)/2;
if(A[mid]==target) return mid;
if(start>=end) return -1;
if(target<A[mid]){
//consider the situation when part of the values that less than A[mid] was rotated to the right.
if(A[mid]>A[end]&&target<A[start]) return helper(mid+1, end, A, target);
else return helper(start, mid-1, A, target);
}
else{
//consider the situation when part of the values that larger than A[mid] was rotated to the left.
if(A[mid]<A[start]&&target>A[end]) return helper(start, mid-1, A, target);
else return helper(mid+1, end, A, target);
}
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: