2020-01-15-sqrtx
LeetCode-69
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 2:
Input: 8
Output: 2
Explanation: The square root of 8 is 2.82842…, and since
the decimal part is truncated, 2 is returned.
Solution
就是手写一个根号源码,首先想到的就是通过平方来做
1 | public int mySqrt(int x) { |
如果不遵循题目的要求,使用Math函数,所以我们的目标大概是3ms附近
1 | public int mySqrt(int x) { |
解法粗暴,遇到大数的时候会从0重新开始计算,复杂度O(N)
第一次优化
思路就是避免做两次乘法然后去比较,这个地方可以去优化
1 | class Solution { |
第二次优化
可以使用二分法来逐步逼近i,没有必要从1开始顺序遍历
1 | class Solution { |