Search in Rotated Sorted Array

Posted torapture

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Search in Rotated Sorted Array相关的知识,希望对你有一定的参考价值。

33. Search in Rotated Sorted Array

class Solution {
public:
    int search(vector<int>& nums, int target) {
        int l = 0, r = nums.size() - 1;
        while (l <= r) {
            int mid = (l + r) / 2;
            if (nums[mid] == target) return mid;
            if (nums[mid] < target) {
                // target on the left side and mid on the right side
                if (target > nums[r] && nums[mid] < nums[l]) r = mid - 1;
                else l = mid + 1;
            } else {
                // target on the right side and mid on the left side
                if (target < nums[l] && nums[mid] > nums[r]) l = mid + 1;
                else r = mid - 1;
            }
        }
        return -1;
    }
};

以上是关于Search in Rotated Sorted Array的主要内容,如果未能解决你的问题,请参考以下文章

Search in Rotated Sorted Array

33. Search in Rotated Sorted Array

33. Search in Rotated Sorted Array

33. Search in Rotated Sorted Array

Leetcode Search in Rotated Sorted Array

33. Search in Rotated Sorted Array *HARD*