跳转至

搜索旋转排序数组⚓︎

Leetcode题目链接

描述⚓︎

详见中文题目链接

解答⚓︎

class Solution {
public:
    int search(vector<int>& nums, int target) {
        int l = -1, r = nums.size();
        while (l + 1 < r) {
            int mid = l + r >> 1;
            if (nums[mid] >= nums[0]) l = mid;
            else r = mid;
        }

        if (target >= nums[0]) r = l + 1, l = -1;
        else r = nums.size();

        while (l + 1 < r) {
            int mid = l + r >> 1;
            if (nums[mid] >= target) r = mid;
            else l = mid;
        }

        if (r < nums.size() && nums[r] == target) return r;
        else return -1;
    }
};