33. Search in Rotated Sorted Array

Problem:

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.

Your algorithm's runtime complexity must be in the order of O(log n).

Example 1:

Input: nums = [4,5,6,7,0,1,2], target = 0
Output: 4

Example 2:

Input: nums = [4,5,6,7,0,1,2], target = 3
Output: -1

思路

Solution (C++):

int search(vector<int>& nums, int target) {
    if (nums.empty()) return -1;
    int n = nums.size(); 
    int pivot = n - 1;
    for (int i = 0; i < n - 1; ++i) {
        if (nums[i] > nums[i+1]) { pivot = i; break; }
    }
    int index = binarySearch(nums, 0, pivot, target);
    if (index == -1) index = binarySearch(nums, pivot+1, n-1, target);
    return index;
    
}
int binarySearch(vector<int>& v, int low, int high, int target) {
    while (low <= high) {
        int mid = low + (high - low) / 2;
        if (v[mid] == target)  return mid;
        else if (v[mid] < target)  low = mid + 1;
        else high = mid - 1;
    }
    return -1;
}

性能

Runtime: 0 ms  Memory Usage: 6.6 MB

思路

Solution (C++):


性能

Runtime: ms  Memory Usage: MB

posted @ 2020-04-01 16:13  littledy  阅读(85)  评论(0编辑  收藏  举报