LeetCode - 33 Search for Rotary Sort Array

Posted by Wave on Fri, 04 Oct 2019 13:22:43 +0200

Problem Description:

Suppose that the array sorted in ascending order rotates at some point that is unknown in advance.

(For example, an array [0, 1, 2, 4, 5, 6, 7] may become [4, 5, 6, 7, 0, 1, 2].

Search for a given target value, return its index if it exists in the array, or return - 1.

You can assume that there are no duplicate elements in the array.

The time complexity of your algorithm must be at the O(log n) level.

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

Source: LeetCode
Link: https://leetcode-cn.com/problems/search-in-rotated-sorted-array
Copyright belongs to the seizure network. For commercial reprints, please contact the official authorization. For non-commercial reprints, please indicate the source.

Implementation results:

Code Description:

class Solution {
public:
    int search(vector<int>& nums, int target) {
        if(nums.size() == 0)    return -1;        // Judge the number of arrays first
        if(nums.size() == 1) 
        {
            return nums[0] == target?0:-1;
        }
        int mid = 0;
        int low = 0;
        int high = nums.size() - 1;
        int i = 0, j = 1;
        for(;j < nums.size(); ++i, ++j)
        {
            if(nums[i] > nums[j])
            {
                mid = i;        // mid is the last number in the first paragraph
                break;
            }
        }
        int res = func(nums, target, low, mid);     // Segment 0-3, paragraph 1 is not satisfied, and then 2
        if(res == -1)
        {
            res = func(nums, target, mid + 1, high);     // 4-6 Notice mid+1 here
        }
        return res;
    }
    
    int func(vector<int> &nums, int target, int start, int end)
    {
        int mid;
        int low = start;
        int high = end;
        while(low <= high)
        {
            mid = low + (high - low)/2;
            if(nums[mid] < target) low = mid + 1;
            else if(nums[mid] > target) high = mid - 1;
            else return mid;        // Note that the return value is the subscript
        }
        return -1;
    }
};

 

Topics: network