leetcode二分查找总结

leetcode33: https://leetcode-cn.com/problems/search-in-rotated-sorted-array/submissions/

class Solution {
public:
    int search(vector& nums, int target)
    {
        int n = nums.size();
        if(n == 0)
        {
            return -1;
        }
        int l = 0;
        int r = n - 1;
        while(l <= r)
        {
            int m = l + (r - l)/2;
            if(nums[m] == target)
            {
                return m;
            }
            if(nums[l] <= nums[m])
            {
                if(nums[m] > target && nums[l] <= target)
                {
                    r = m - 1;
                }
                else
                {
                    l = m + 1;
                }
            }
            else
            {
                if(nums[m] < target && nums[r] >= target)
                {
                    l = m + 1;
                }
                else
                {
                    r = m - 1;
                }
            }

        }
        return -1;

    }
};

 

你可能感兴趣的:(leetcode刷题笔记)