Leetcode 33. 搜索旋转排序数组

序列为两个升序,给后面的升序(都小于第一个元素)加一个权值,使序列变为一个升序,然后二分查找

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

猜你喜欢

转载自blog.csdn.net/Bendaai/article/details/80059676
今日推荐