旋轉已排序數組中查找

1. 數組中無重複元素數組

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]).spa

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

You may assume no duplicate exists in the array.blog

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

Example 1:get

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

Example 2:it

Input: nums = [, target = 3
Output: -1

1.1 尋找最小值所在的點
創建模型求解
4,5,6,7,0,1,2]

本題關鍵在於求解 最小值所在的索引,再經過二分法求解便可。class

選擇right做爲比較的軸值,緣由在於nums[right] 永遠不會等於nums[mid],分一下三種狀況討論。循環

若是中間值比最右端的值大,那麼應該讓 left = mid + 1,若是中間值比最右端小,那麼應該讓right = mid,由於nums[mid] = y1時也是知足中間值比最右端小,不該該讓right = mid - 1.im

循環結束時left = right = index(y1)

 1.2 二分法求解

先按照標準的二分法思路求解,不一樣的是,旋轉之後,中間值與未旋轉以前老是向後偏移最小值索引個單位。

 int search(vector<int>& nums, int target) {
    int left = 0;
    int right = nums.size() - 1;
    int mid = 0;

    while (left < right) {
        mid = (left + right) / 2;
        if (nums[mid] <= nums[right]) {
            right = mid;
        }
        else {
            left = mid + 1;
        }
    }
    int point = left;
    left = 0;
    right = nums.size() - 1;
    while (left <= right) {
        int medium = (left + right) / 2;
        mid = (medium + point) % nums.size();
        if (nums[mid] < target) {
            left = medium + 1;
        }
        else if (nums[mid] > target) {
            right = medium - 1;
        }
        else {
            return mid;
        }
    }
    return -1;
}
相關文章
相關標籤/搜索