Leetcode 69. Sqrt(x)
69. Sqrt(x)
Total Accepted: 99997 Total Submissions: 388728 Difficulty: Medium
Implement int sqrt(int x)
.
Compute and return the square root of x.
思路:可以直接用sqrt函数。但实际上这题考察的是二分查找,二分查找实际比较容易写错。最终返回的是左边最靠*x*方根的数,考虑左闭右开。
代码:
最简单的方法:
1 class Solution { 2 public: 3 int mySqrt(int x) {//1579205274 4 int half=(int)sqrt(x); 5 return half; 6 } 7 };
二分查找:左闭右开:left有效,right无效。
形式一:
1 class Solution { 2 public: 3 int mySqrt(int x) { 4 int left=0,right=x; 5 while(left<right){ 6 int mid = right - (right-left)/2; 7 if(mid<=x/mid) left=mid; 8 else{ 9 right=mid-1; 10 } 11 } 12 return left; 13 } 14 };
形式二:
1 class Solution { 2 public: 3 int mySqrt(int x) {//1579205274 4 if(x<=1){ 5 return x; 6 } 7 //左闭右开,所以初始化时,right>left 8 int mid,left=1,right=x; 9 while(left<right){ 10 mid=left+(right-left)/2; //写成(right+left)/2,会造成溢出 11 if(x/mid>=mid){ 12 left=mid+1; 13 } 14 else{ 15 right=mid; 16 } 17 } 18 return left-1; 19 } 20 };