凡是要在一堆元素里寻找某个特定元素或其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是: