首页 > 其他 > 详细

[LeetCode] Sqrt(x)

时间:2015-02-25 19:52:21      阅读:256      评论:0      收藏:0      [点我收藏+]

Implement int sqrt(int x).

Compute and return the square root of x.

 

解法:二分搜索

    时间复杂度O(logN), 空间复杂度O(1)

 1 class Solution {
 2 public:
 3     int sqrt(int x) {
 4         int low = 1;
 5         int high = x / 2;
 6         int mid, ans;
 7         
 8         if (x < 2) return x;
 9         
10         while (low <= high) {
11             mid = low + (high - low) / 2;
12             if (mid <= x / mid) {
13                 low = mid + 1;
14                 ans = mid;
15             } else {
16                 high = mid - 1;
17             }
18         }
19         
20         return ans;
21     }
22 };

 

[LeetCode] Sqrt(x)

原文:http://www.cnblogs.com/vincently/p/4299988.html

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