您的位置:首页 > 其它

Search in Rotated Sorted Array 【新思路】

2015-03-12 13:16 155 查看
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.

思路:1.在做完findMin之后,对做rotated很有启发。 2.以前写的花了40ms,具体什么方法还没回顾。 我终于懂了rotated是啥了。轮转暗暗

注意 findmin中while(a<b); rotated binary search中while(a<=b); Σ( ° △ °|||)︴介个好捉急。待我,想想怎么把while里面带不带=的问题解决掉。

findMin里while(a<b)不带等号原因: if a==b, it means only one element in array, so a is the min, don't need to find again.

rotated binary search里while(a<=b)带等号的原因, target need to compare with num[a] or num[b], so compare is still need!

class Solution {
public:
/*find the min, then use binary search to find target*/
int search(int A[], int n, int target) {
int a=0,b=n-1,mid=0;
while(a<b){
mid = (a+b)/2;
if(A[mid]>A[b]) a=mid+1;
else b=mid;
}
int indexOfMin = a;
/*-----binary search----*/
int offset=indexOfMin; //if not rotated, min is the start element
a=0;b=n-1;
while(a<=b){
mid=(a+b)/2;
int realMid=(mid+offset)%n;
if(target == A[realMid]) return realMid;
else if(target<A[realMid]) b=mid-1;
else a=mid+1;
}
return -1;

}

};


算法里巧妙的地方在于 使用offset寻找realMid, target与A[realMid]比较,判断下一轮计算的realMid应该更小,还是更大。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: