33. 搜索旋转排序数组

33. 搜索旋转排序数组_第1张图片

int search(vector &nums, int target) {
    if (nums.size() == 0)
        return -1;
    if (nums.size() == 1)
        return target == nums[0] ? 0 : -1;

    int l = 0, r = nums.size() - 1;
    while (l <= r) {
        int mid = l + ((r - l) >> 1);
        if (nums[mid] == target)
            return mid;
        else if (nums[0] <= nums[mid]) {
            if (nums[0] <= target && target < nums[mid])
                r = mid - 1;
            else
                l = mid + 1;
        } else if (nums[0] > nums[mid]) {
            if (nums[mid] < target && target <= nums[nums.size() - 1])
                l = mid + 1;
            else
                r = mid - 1;
        }
    }
    return -1;
}

你可能感兴趣的:(33. 搜索旋转排序数组)