[勇者闯LeetCode] 69. Sqrt(x)
Description
Implement
int sqrt(int x)
.
Compute and return the square root o x.
Information
- Tags: Binary Search | Match
- Difficulty: Easy
Solution
使用二分搜索,算法复杂度为O(logN).
class Solution(object):
def mySqrt(self, x):
"""
:type x: int
:rtype: int
"""
if x == 0:
return 0
start, end = 1, x
while (end >= start):
mid = start + (end - start) // 2
s = x // mid
if (mid == s):
return mid
elif (mid < s):
start = mid + 1
else:
end = mid - 1
return end