您的位置:首页 > 其它

leetcode Sqrt(x) 求开方

2017-09-20 16:36 316 查看
Implement int sqrt(int x).

Compute and return the square root of x.

class Solution {
public:
int mySqrt(int x) {
if (x == 0) return 0;
int left = 1, right = INT_MAX;
while(1) {
int mid =left + (right - left) / 2;
if (mid > x / mid)
right = mid - 1;
else {
if (mid + 1 > x / (mid + 1))
return mid;
left = mid + 1;
}
}
}
};


直接暴力搜索会超时,所以使用二分法的思想来做,时间复杂度o(log x)。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: