Leetcode日练笔记2 #69 #374 #33 sqrt() & Guess Number Higher or Lower & Search in Rotated Sorted Array

凡是要在一堆元素里寻找某个特定元素或其index的时候,都用binary search。

#69 求开根

Given a non-negative integer x, compute and return the square root of x.

Since the return type is an integer, the decimal digits are truncated, and only the integer part of the result is returned.

Note: You are not allowed to use any built-in exponent function or operator, such as pow(x, 0.5) or x ** 0.5.

也是从中间开始找开根值,一开始其平方会大过给定值。

再取半,当出现其平方小于给定值时,缩小取值范围再取半。缩小范围用左标右标框着。

直到最后剩相邻的两个值,输出左标。

之所以左标从0开始,是为了囊括x=0的情况。

一开始先看x是不是1,是为了排除x=1之后,left会无法挪动依旧为0,而输出0的情况。

(不过不太理解constraint在这里是?需要我干什么?)

class Solution:
    def mySqrt(self, x: int) -> int:
        left, right = 0, x
        if x == 1:
            return x  
        while right-left > 1:
            square_root = left + (right - left + 1)//2
            if square_root*square_root > x:
                right = square_root
            else:      
                left = square_root
        return left

runtime表现:

22ms的solution是:


                
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值