[Leetcode] 33. Search in half Rotated Sorted Array circulating ordered array lookup

 

1. Topic

Suppose a sorted array 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.

2. Ideas

First find the minimum value index, then according to the comparison results to determine which section orderly array binary search.
Find the minimum value by recursion. For a certain period of cycles ordered array, divided into two sections positioned to find two, preceding the first node is tail node is equal to the subsequent stage, i.e. there is an intersection, to avoid missing. If the two are ordered, indicating that overall is ordered to return to the first node of the previous stage. If a section of the first is greater than the tail, the recursive lookup in this paragraph there.

3. Code

class Solution {
public:
    // 先找到最小点,然后在在其中一边做二分查找。
    // 如果是有序的, 则末端大于首端; 基于此可以二分定位到最小点
    int search(vector<int>& nums, int target) {
        int sz = nums.size();
        if (sz == 0) return -1;
        if (sz == 1) return nums[0] == target ? 0 : -1;
        int min_idx = find_min_idx(nums, 0, nums.size());
        //cout << min_idx << " " << nums[min_idx] << endl;
        if (target <= nums[sz-1]) {
            return bsearch(nums, min_idx, sz, target);
        } else {
            return bsearch(nums, 0, min_idx, target);
        }
    }
    
    int find_min_idx(vector<int>& nums, int i, int j) {
        if (i >= j) return -1;
        if (j - i == 1) return i;
        if (j - i == 2) return nums[i] > nums[j-1] ? j-1 : i;
        int k = (i + j) / 2;
        if (nums[k] < nums[i]) {
            return find_min_idx(nums, i, k+1);
        } else if (nums[k] > nums[j-1]) {
            return find_min_idx(nums, k, j);
        } else {
            return i;
        }
    }
    
    int bsearch(vector<int>& nums, int i, int j , int target) {
        if (j <= i) return -1;
        int k = (i + j) / 2;
        if (nums[k] == target) {
            return k;
        } else if (nums[k] > target) {
            return bsearch(nums, i, k, target);
        } else {
            return bsearch(nums, k+1, j, target);
        }
    }
};
Published 17 original articles · won praise 2 · views 50000 +

Guess you like

Origin blog.csdn.net/u011250186/article/details/103865201
Recommended