33. Search in Rotated Sorted Array (Medium)

Suppose an array sorted in ascending order is rotated at some pivot unknown to you beforehand.

(i.e., 0 1 2 4 5 6 7 might become 4 5 6 7 0 1 2).

You are given a target value to search. If found in the array return its index, otherwise return -1.

You may assume no duplicate exists in the array.

Solution: Binary Search 9ms

Time Complexity: $$O(logn)$$

class Solution {
public:
    int search(vector<int>& nums, int target) {
        int n = nums.size();
        int lo = 0, hi = n-1;
        // find pivot
        while (lo < hi) {
            int mid = (lo+hi)/2;
            if (nums[mid] > nums[hi]) lo = mid+1;
            else hi = mid;
        }

        hi = lo+n-1;
        while (lo <= hi) {
            int mid = (lo+hi)/2;
            int id = mid % n;
            if (nums[id] == target) return id;
            else if (nums[id] < target) lo = mid+1;
            else hi = mid-1;
        }
        return -1;
    }
};

results matching ""

    No results matching ""