*LeetCode-Search in Rotated Sorted Array

思路就是首先找到pivot 也就是最小的那个数 然后就可以通过pivot来矫正head tail mid的真正位置 从而可以进行正常的binary search了 

找pivot的时候就是一个二分查找 每次用mid 和 tail比较 但是注意挪动head 或者tail的时候的细节 假如mid < tail tail不是直接mid -1 而是tail = mid

 然后第二遍search的时候 注意公式 realHead = head + pivot   realTail = tail + pivot    readMid = (head + pivot + tail + pivot ) / 2 但是可能超出length 所以要%length

同时也要注意每次用realMid取数字 但是每次挪动head tail是用原来的mid!!!

public class Solution {
    public int search(int[] nums, int target) {
        int head = 0;
        int tail = nums.length - 1;
        while ( head < tail ){
            int mid = ( head + tail ) / 2;
            if ( nums[ mid ] > nums[ tail ] )
                head = mid + 1;
            else if ( nums[ mid ] < nums [ tail ] )
                tail = mid;
        }
        int pivot = head;
        head = 0;
        tail = nums.length - 1;
        while ( head <= tail ){
            int mid = ( head + tail ) / 2;
            int realmid = ( mid + pivot ) % nums.length;
            if ( nums[ realmid ] > target )
                tail = mid - 1;
            else if ( nums[ realmid ] < target )
                head = mid + 1;
            else 
                return realmid;
        }
        return -1;
    }
}


你可能感兴趣的:(*LeetCode-Search in Rotated Sorted Array)