题解 | #二分查找-一种直接赋值middle给left/right的方法I#

二分查找-I

http://www.nowcoder.com/practice/d3df40bd23594118b57554129cadf47b

int search(vector<int>& nums, int target) {
    // write code here
    int len = nums.size();
    if(len<=0) return -1;
    int left = 0;
    int right = len-1;
    
    int middle = (left + right)/2;//防止溢出写法另鉴
    
    if(nums[0]==target) return 0;
    if(nums[len-1]==target) return len-1;
    
    while(middle!=left&&middle!=right)
    {
        if(nums[middle]<target)
            left=middle;        
        else if(nums[middle]>target)
            right = middle;
        else if(nums[middle]==target)
            return middle;
        
        middle = (left+right)/2;
    }
    
        return -1;
}

};

全部评论

相关推荐

贪食滴🐶:你说熟悉扣篮的底层原理,有过隔扣职业球员的实战经验吗
点赞 评论 收藏
分享
评论
点赞
收藏
分享
牛客网
牛客企业服务