81. Search in Rotated Sorted Array II

重复时候r--

bool search(int* nums, int numsSize, int target) {
    int l = 0;
    int r = numsSize - 1;
    int mid = 0;
    while(l+1 < r){
        mid = l + (r-l)/2;
        if(nums[mid] == target)
            return true;
        if(nums[mid] < nums[r]){
            //right is ordered
            //if target locates a right parits
            if(target <= nums[r] && target >= nums[mid])
                l = mid;
            else
                r = mid;
        }else if(nums[mid] > nums[r]){
            //left is ordered
            if(target<= nums[mid] && target >= nums[l])
                r = mid;
            else
                l = mid;
        }else
            r--;
    }
    
    if(nums[l] == target)
        return true;
    
    if(nums[r] == target)
        return true;
    
    return false;
    

你可能感兴趣的:(81. Search in Rotated Sorted Array II)