您的位置:首页 > 编程语言 > Go语言

[勇者闯LeetCode] 69. Sqrt(x)

2017-03-05 21:03 603 查看

[勇者闯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
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  algorithm leetcode