ARTS 第十三周

发布于 September 12, 2019

Algorithm

69. Sqrt(x)

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 1:

Input: 8
Output: 2
Explanation: The square root of 8 is 2.82842..., and since 
             the decimal part is truncated, 2 is returned.
import "sort"
func mySqrt(x int) int {
    return sort.Search(x+1, func(i int) bool {
        return i*i > x
    }) - 1
}

sort.Search() 方法会使用“二分查找”算法来找出能使 f(x)(0<=x<n) 返回 ture 的最小值 i。 前提条件: f(x)(0<=x<i) 均返回 false, f(x)(i<=x<n) 均返回 ture。如果不存在 i 可以使 f(i) 返回 ture,则返回 n

Review

Deep Learning with Python - Chapter 5

Share

HTTP API 认证授权术

E