mirror of
https://github.com/halfrost/LeetCode-Go.git
synced 2025-07-06 09:23:19 +08:00
Merge pull request #146 from hanlins/69/sqrtx/consise-binary-search
Make the binary search solution more concise for Sqrt x
This commit is contained in:
@ -1,23 +1,18 @@
|
||||
package leetcode
|
||||
|
||||
// 解法一 二分
|
||||
// 解法一 二分, 找到最后一个满足 n^2 <= x 的整数n
|
||||
func mySqrt(x int) int {
|
||||
if x == 0 {
|
||||
return 0
|
||||
}
|
||||
left, right, res := 1, x, 0
|
||||
for left <= right {
|
||||
mid := left + ((right - left) >> 1)
|
||||
if mid < x/mid {
|
||||
left = mid + 1
|
||||
res = mid
|
||||
} else if mid == x/mid {
|
||||
return mid
|
||||
l, r := 0, x
|
||||
for l < r {
|
||||
mid := (l + r + 1) / 2
|
||||
if mid*mid > x {
|
||||
r = mid - 1
|
||||
} else {
|
||||
right = mid - 1
|
||||
l = mid
|
||||
}
|
||||
}
|
||||
return res
|
||||
|
||||
return l
|
||||
}
|
||||
|
||||
// 解法二 牛顿迭代法 https://en.wikipedia.org/wiki/Integer_square_root
|
||||
|
Reference in New Issue
Block a user