1、换函数exp()(0ms,100%;6.2MB,5%)
1 int mySqrt(int x) { 2 if(x==0) 3 return x; 4 int num=exp(0.5*log(x)); 5 if(long (num+1)*(num+1)<=x) 6 return num+1; 7 else 8 return num; 9 }
2、二分查找(4ms,59%;5.8MB,64%)
1 int mySqrt(int x) { 2 if(x<=1) 3 return x; 4 long left=1,right=x; 5 long mid=(left+right)/2; 6 while(left<=right){ 7 //因为很多数的算数平方根是夹在两个数中间的 8 if(((mid*mid)<=x)&&((mid+1)*(mid+1)>x)) 9 return mid; 10 //mid偏小,整体往右移动 11 else if((mid*mid)<x){ 12 left=mid+1; 13 mid=(left+right)/2; 14 } 15 //mid偏大,整体往右移动 16 else { 17 right=mid-1; 18 mid=(left+right)/2; 19 } 20 21 } 22 return 0; 23 }
3、牛顿迭代(4ms,59%;5.8MB,60%):没看懂
1 int mySqrt(int x) { 2 if (x == 0) { 3 return 0; 4 } 5 6 double C = x, x0 = x; 7 while (true) { 8 double xi = 0.5 * (x0 + C / x0); 9 if (fabs(x0 - xi) < 1e-7) { 10 break; 11 } 12 x0 = xi; 13 } 14 return int(x0); 15 }