首页 > 其他 > 详细

【LeetCode】Sqrt(x)

时间:2019-09-13 20:46:35      阅读:71      评论:0      收藏:0      [点我收藏+]

【Description】

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.

【AC code】

一、暴力法   时间复杂度:O(sqrt(x))

技术分享图片
1 class Solution {
2     public int mySqrt(int x) {
3         if (x <= 1) return x;
4         int t = 1;
5         while (x / t >= t) t++;
6         return t - 1;
7     }
8 }
View Code

二、二分查找法  时间复杂度:O(logn)

技术分享图片
 1 class Solution {
 2     public int mySqrt(int x) {
 3         if (x <= 1) return x;
 4         int left = 1, right = x;
 5         while (left <= right) {
 6             int mid = left + (right - left) / 2;
 7             if (x / mid > mid) left = mid + 1;
 8             else if (x / mid < mid) right = mid - 1;
 9             else return mid;
10         }
11         return left - 1;
12     }
13 }
View Code

三、牛顿迭代法  时间复杂度:O(logn)

Referencehttps://www.cnblogs.com/AnnieKim/archive/2013/04/18/3028607.html

技术分享图片
 1 class Solution {
 2     public int mySqrt(int x) {
 3         if (x <= 1) return x;
 4         long t = x; //测试用例中x的最大值为INT_MAX,为避免后续(t + x / t)数据溢出采用long。
 5         while (x / t < t) {
 6             t = (t + x / t) / 2;
 7         }
 8         return (int)t;
 9     }
10 }
View Code

【LeetCode】Sqrt(x)

原文:https://www.cnblogs.com/moongazer/p/11514565.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!