[LeetCode] 69. Sqrt(x)_Easy tag: Binary Search

Implement int sqrt(int x).

Compute and return the square root of x, where x is guaranteed to be a non-negative integer.

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

Example 1:

Input: 4
Output: 2

Example 2:

Input: 8
Output: 2
Explanation: The square root of 8 is 2.82842..., and since
  the decimal part is truncated, 2 is returned. 04/15/2019 UPdate: 利用binary search,找last index that i * i <= x. Time: O(lg n) , Space: O(1) Code
class Solution:
def sqrt(self, x):
if x < 2: return x
l, r = 1, x # r * r > x for sure
while l + 1 < r:
mid = l + (r - l)//2
value = mid * mid
if value > x:
r = mid
elif value < x:
l = mid
else:
return mid
return l

class Solution:
def sqrt(self, num):
ans = num
while ans*ans > num:
ans = (ans + num//ans)//2
return ans
上一篇:2016.10.17 yaml文件里的labels和Pod、RC、Service的对应关系


下一篇:RPA赋能新零售,加紧开辟新战场