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

相关链接如下:

知乎:littledy

欢迎关注个人微信公众号:小邓杂谈,扫描下方二维码即可

作者:littledy
本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文链接,否则保留追究法律责任的权利。
原文地址:https://www.cnblogs.com/dysjtu1995/p/12613344.html