LC 33. Search in Rotated Sorted Array

Problem Description

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

Answers

class Solution {
public:
    int search(vector<int>& nums, int target) {
        if(nums.size() == 0) return -1;
        int l = 0;
        int r = nums.size()-1;
        while(l<r){
            int mid = (l+r)>>1;
            if(nums[l]<=nums[mid]){
                if(target<=nums[mid] && target >= nums[l]) r = mid;
                else l = mid +1;
            }else if(nums[mid]<nums[r]){
                if(target>nums[mid] && target <= nums[r]) l = mid +1;
                else r = mid;
            }
        }
        if(target == nums[l]) return r;
        return -1;
    }
};

 

The answer description

Not knowing whether the ordered sequence, so when making binary search, you need to determine at what interval:

1. Low <median: mean from low to median, must be ordered. If the connection point of the cycle, not over the median, then the median lower altitude, low altitude higher this time, the number of columns in an orderly,

2. Median <high: between, this paragraph there is orderly, it is possible to search within this interval.

Purpose and keep order.

 

Guess you like

Origin www.cnblogs.com/kykai/p/11769048.html
Recommended