代码随想录-数组篇

2-二分查找

方法一:

左闭右闭,[left, right]
代码随想录-数组篇_第1张图片

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

方法二:

左闭右闭,[left, right]
代码随想录-数组篇_第2张图片

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

链接

你可能感兴趣的:(C++学习,算法)