33. Search in Rotated Sorted Array 旋转排序数组极值的二分求法

Suppose an array sorted in ascending order 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.

class Solution {
public:
    int search(vector& nums, int target) {
        int n = nums.size();
        int lo = 0, hi = n - 1;
        while(lo < hi){//find smallest
            int mid = (lo + hi) / 2;
            if(nums[mid] > nums[hi]) lo = mid + 1;// 这里 nums[mid] > nums[hi] 一定大于 所以要 +1
            else hi = mid;// (lo + hi) / 2 会使mid 一定小于hi 已经至少减1了 无需 hi = mid;
        }
        int L, R;
        if(lo == 0){//如果n == 1 ,lo必等于0,必进这个分支
            L = 0;
            R = n - 1;
        }else if(target >= nums[0]){
            L = 0;
            R = lo - 1;
        }else{
            L = lo;
            R = n - 1;
        }
        while(L <= R){
            if(target > nums[R] || target < nums[L] ) return -1;
            int mid = (L + R) / 2;
            if(nums[mid] == target) return mid;
            else if(nums[mid] > target) R = mid - 1;//类似于第8行 一定要 -1
            else L = mid + 1;
        }
        
        return L;
        
    }
};


你可能感兴趣的:(二分)