题解 | #二分查找#

二分查找

http://www.nowcoder.com/practice/7bc4a1c7c371425d9faa9d1b511fe193

好难啊。

我之前尝试用递归失败了, 最后写了个循环的

class Solution:
    def upper_bound_(self , n , v , a ):
        # write code here
        low, high = 0 , n-1
        res = n + 1
        while low <= high:
            mid = (high - low) // 2 + low
            num = a[mid]
            if num < v:   
                # 往右边移动
                low = mid + 1
            else:
                high = mid - 1
                res = mid + 1
        return res

全部评论

相关推荐

点赞 收藏 评论
分享
牛客网
牛客企业服务