题目: [4, 5, 6, 7, 0, 1, 2]
给出数字0, 返回0的索引4。
class Solution {
public:
int search(int A[], int n, int target) {
int lo=0,hi=n-1;
// find the index of the smallest value using binary search.
// Loop will terminate since mid < hi, and lo or hi will shrink by at least 1.
// Proof by contradiction that mid < hi: if mid==hi, then lo==hi and loop would have been terminated.
while(lo<hi){
int mid=(lo+hi)/2;
if(A[mid]>A[hi]) lo=mid+1;
else hi=mid;
}
// lo==hi is the index of the smallest value and also the number of places rotated.
int rot=lo;
lo=0;hi=n-1;
// The usual binary search and accounting for rotation.
while(lo<=hi){
int mid=(lo+hi)/2;
int realmid=(mid+rot)%n;
if(A[realmid]==target)return realmid;
if(A[realmid]<target)lo=mid+1;
else hi=mid-1;
}
return -1;
}
};
后面的readmid看的头痛,遇到这种绕的东西就难受。记下来,过几天再看。
1.10号续:
过了两天一下就看懂了。
这道算法题的难点在于,本来的有序数组前半段进行倒换后,变到了数组末尾,因此不能直接使用二分法进行比较。因此,解题时候分为两步,首先找到倒换的支点,这样就能将原数组分为两个有序数组。然后在第一步的基础上,或者将数组还原成有序,或者分别对两个有序子数组进行处理。这里采用第一种思路。
第一个while循环找到对用的rotate点,例子中0的位置。
这里有个问题,就是能否找最大的点作为支点(例子中的9)。答案是不能。因为偶数个的时候,寻找middle的过程中,只会落在左边的店(较小点)上。使后续的寻找不能成功,可以自己举例仔细想想。
在第二步, 需要知道的是,原来的数组是一个有序的数组,因此直接找中间的位置就是在原来的数组中正常的middle位置。但此时的数组是偏移后的,将原数组的index进行同样的操作就能找到middle在现在数组中的位置,进行比较。总结来说就是,假装数组仍然是有序的,但在比较的时候需要找到真正的middle位置比较。其他操作都在假设输入仍然是有序的样子进行。因为最终输出的是realmid,所以结果不受影响。