Implement int sqrt(int x).
Compute and return the square root of x.
x is guaranteed to be a non-negative integer.
Example 1:
Input: 4
Output: 2
Example 2:
Input: 8
Output: 2
Explanation: The square root of 8 is 2.82842...,
and since we want to return an integer, the decimal part will be truncated.
解题思路:
此题目实现Python中 int(math.sqrt(x)) 的功能。简单方法就是从0开始循环,找到当前数的平方不大于x的但下一个数的平方大于x的数,然后返回当前数。但是这种做法时间复杂度为O(n^(1/2)),会超时。
可以借助二分查找的思想,时间复杂度降为 O(lgn)。
Python实现:
class Solution:
def mySqrt(self, x):
"""
:type x: int
:rtype: int
"""
if x == 0 or x == 1: # 注意 0, 1 这两个特殊的数字
return x
low = 0; high = x
while low <= high:
mid = (low + high) // 2
if mid ** 2 <= x < (mid + 1) ** 2:
return mid
elif mid ** 2 > x:
high = mid
else:
low = mid
return 0
a = 8
b = Solution()
print(b.mySqrt(a)) # 2
网友评论