0
点赞
收藏
分享

微信扫一扫

Leetcode二分查找2:704. 二分查找

嚯霍嚯 2022-03-18 阅读 92

链接:https://leetcode-cn.com/problems/binary-search/icon-default.png?t=M276https://leetcode-cn.com/problems/binary-search/

 这题是二分查找的板子。

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

相关推荐

0 条评论