Leetcode 81. Search in Rotated Sorted Array II

文章作者:Tyan
博客:noahsnail.com  |  CSDN  | 

1. Description

Leetcode 81. Search in Rotated Sorted Array II_第1张图片
Search in Rotated Sorted Array II

2. Solution

class Solution {
public:
    bool search(vector& nums, int target) {
        int size = nums.size();
        int left = 0;
        int right = size - 1;
        while(left <= right) {
            int mid = (left + right) / 2;
            if(nums[mid] == target) {
                return true;
            }
            if(nums[left] == nums[mid]) {
                left++;
                continue;
            }
            if(nums[left] < nums[mid]) {
                if(target >= nums[left] && target <= nums[mid]) {
                    right = mid - 1;
                }
                else {
                    left = mid + 1;
                }
            }
            else {
                if(target >= nums[mid] && target <= nums[right]) {
                    left = mid + 1;
                }
                else {
                    right = mid - 1;
                }
            }
        }
        return false;
    }
};

Reference

  1. https://leetcode.com/problems/search-in-rotated-sorted-array-ii/description/

你可能感兴趣的:(Leetcode 81. Search in Rotated Sorted Array II)