33. Search in change of direction Rotated Sorted Array dichotomy of use

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.

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

Reference: https://blog.csdn.net/qq_26410101/article/details/80665577

Problem-solving ideas:

Since time is required complexity O (log n), then it should be dichotomy. From the title you can see the array is ordered, if the array is divided into two parts in the middle, then at least a part is ordered, then how to determine that part of the array is ordered? When the calculated number of columns of this intermediate, i.e. (left + right) / 2, how mid> right, the left column is the number ordered. If the mid <right, then the number of columns on the right are ordered. When that part is ordered to find out the number of columns, you can use to find a dichotomy (premise dichotomy is the number of columns must be ordered). If the ordered number if the number of columns in that part, the binary search, if the number is uncertain whether an ordered sequence to the inside, then continued the series into two parts, to find that part of the order, and then returned to the above steps.

If you do not understand the above ideas, links can refer to offer, there are examples that can help to understand.

Note: When performing a binary search, change the value of the left and right of the time, must be left, right = mid + 1 or mid-1, can not be left, right = mid, otherwise it would have been caught in an infinite loop.

class Solution {
public:
    int search(vector<int>& nums, int target) {
        int cnt = nums.capacity();
        int left = 0, right = cnt-1;
        int mid = cnt / 2;
        while(left<=right) {
            mid = (left + right) / 2;
            if(nums[mid]==target) return mid;
            if(nums[mid] > nums[right]) {
                // left
                if(target>=nums[left] && target <=nums[mid]) {
                    right = mid-1;
                }
                else {
                    left = mid+1;
                }
            }
            else {
                if(target>=nums[mid] && target <=nums[right]) {
                    left = mid+1;
                }
                else {
                    right = mid-1;
                }
            }
        }
        return -1;
    }
};

 

Published 147 original articles · won praise 29 · Views 100,000 +

Guess you like

Origin blog.csdn.net/Haskei/article/details/104073961