[Binary search] leetcode 33 Search in Rotated Sorted Array

problem: https://leetcode.com/problems/search-in-rotated-sorted-array/

        Binary search topic. Half meets the conditions of increasing check-half later, we met and if the data falls in this range, will find in this section, or to look for another interval.

class Solution {
public:
    int search(vector<int>& nums, int target) {
        if(!nums.size()) return -1;
        int low = 0;
        int high = nums.size() - 1;
        while (low < high) 
        {
            int mid = (low + high) / 2;
            if (nums[mid] == target) return mid;
        
            if (nums[low] <= nums[mid]) 
            {
                if (target >= nums[low] && target < nums[mid])  // it's ascending
                {
                    high = mid - 1;
                } 
                else {
                    low = mid + 1;
                }
            } 
            else 
            {
                if (target > nums[mid] && target <= nums[high])   // it's ascending
                {
                    low = mid + 1;
                } 
                else 
                {
                    high = mid - 1;
                }
            }
        }
        return nums[low] == target ? low : -1;
    }
};

 

Guess you like

Origin www.cnblogs.com/fish1996/p/11333732.html