代码随想录 Leetcode704. 二分查找

题目:


代码(首刷自解 2023年12月28日):

class Solution {
public:
    int search(vector& nums, int target) {
        // 左闭右开
        int n = nums.size();
        int left = 0, right = n;
        int mid = 0;
        while(left target){
                // 因为左闭右开,所以right不会取到mid
                right = mid;
            }else if(nums[mid] < target){
                // 因为左闭右开,所以left会取到mid,所以要+1
                left = mid + 1;
            }else{
                return mid;
            }
        }
        return -1;
    }
};

你可能感兴趣的:(#,leetcode,---,easy,前端,算法,javascript)