LeetCode 81. Search in Rotated Sorted Array II

描述

在循环数组中,查找是否存在目标值

解决

二分查找


class Solution {
public:
    bool search(vector<int>& nums, int target) {
        int length = nums.size();
        int l = 0, r = length - 1;
        while (l < r)
        {
            int m = l + ((r - l) >> 1);
           // cout << nums[m] << endl;
            if (nums[m] == target)
                return true;
            if (nums[l] < nums[m])
            {
                if (nums[l] <= target && target < nums[m])
                    return binary_search(&nums[l], &nums[m], target);
                else
                    l = m;
            }
            else if (nums[l] > nums[m])
            {
                if (nums[r] >= target && target > nums[m])
                    return binary_search(&nums[m] + 1, &nums[r] + 1, target);
                else
                    r = m - 1;
            }
            else
                ++l;
        }
        if (nums[l] == target)
            return true;
        return false;
    }
};

你可能感兴趣的:(二分查找)