LeetCode 81 Search Rotated Sorted Array

  • analysis

    Compared with LeetCode 33, this problem may have duplicate numbers in the array, so special processing is required. Because this time you have to search both to the left and to the right. The key logic has been introduced in detail in this blog https://blog.csdn.net/xiaoan08133192/article/details/108438402

  • Code
class Solution {
public:
    bool find(vector<int>& nums, int start, int end, int target){
        if(start > end || start >= nums.size()){
            return false;
        }

        int mid = (start + end) / 2;
        if(nums[mid] == target){
            return true;
        }

        if(nums[mid] == nums[start]){//这个时候既要向左搜也要向又搜
            return find(nums, start, mid - 1, target) || find(nums, mid + 1, end, target);
        }

        if(nums[mid] > nums[start] && target >= nums[start] && target < nums[mid] || 
           nums[mid] < nums[start] && target < nums[mid] ||
           nums[mid] < nums[start] && target >= nums[start]){
               return find(nums, start, mid - 1, target);
        }else{
            return find(nums, mid + 1, end, target);
        }
    }
    bool search(vector<int>& nums, int target) {
        return find(nums, 0, nums.size(), target);
    }
};

 

Guess you like

Origin blog.csdn.net/xiaoan08133192/article/details/108560510