【LeetCode】81. Search Rotation Sorted Array II

topic

It is known that there is an integer array nums arranged in non-descending order, and the values ​​in the array do not have to be different from each other.
Before being passed to the function, nums is rotated on a pre-unknown subscript k (0 <= k < nums.length), so that the array becomes [nums[k], nums[k+1], …, nums[n-1], nums[0], nums[1], …, nums[k-1]] (subscripts start counting from 0). For example, [0,1,2,4,4,4,5,6,6,7] could become [4,5,6,6,7,0,1,2, 4,4].
Given your rotated array nums and an integer target, please write a function to determine whether the given target value exists in the array. Returns true if the target value target exists in nums, otherwise returns false.
You have to minimize the whole operation steps as much as possible.

Example 1:

Input: nums = [2,5,6,0,0,1,2], target = 0
Output: true

Example 2:

Input: nums = [2,5,6,0,0,1,2], target = 3
Output: false

hint:

1 <= nums.length <= 5000
-104 <= nums[i] <= 104
The title data guarantees that nums is rotated on a pre-unknown subscript
-104 <= target <= 104

Advanced:

This is an extended topic of searching a rotated sorted array, where nums may contain duplicate elements.
Will this affect the time complexity of the program? What will be the impact and why?

answer

Use pseudo-binary search to find
that there must be an ordered side on the left and right of mid

class Solution {
    
    
public:
    bool search(vector<int>& nums, int target) {
    
    
        int left = 0;
        int right = nums.size()-1;
        while(left<=right)
        {
    
    
            int mid = left + ((right-left)>>1);

            if(nums[mid] == target)
                return true;

            if(nums[left] == nums[mid] && nums[mid] == nums[right])
            {
    
    
                left++;
                right--;
            }
            else if(nums[left]<=nums[mid])
            {
    
    
                if(nums[left]<=target && target<nums[mid])
                {
    
    
                    right = mid-1;
                }
                else
                {
    
    
                    left = mid+1;
                }
            }
            else if(nums[mid]<=nums[right])
            {
    
    
                if(nums[mid]<target && target<=nums[right])
                {
    
    
                    left = mid+1;
                }
                else
                {
    
    
                    right = mid-1;
                }
            }
        }
        return false;
    }
};

Guess you like

Origin blog.csdn.net/qq_45972928/article/details/126372012