69. Sqrt(x)
问题:
求开平方x后取整的值。
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.
解法:二分查找(Binary Search)
搜索范围:[l,r) 左闭右开区间。
模版:
1 int binary_search(int l, int r, int x) { 2 // range: [l,r) 3 while(l<r) { 4 int m = l+(r-l)/2; 5 if(f(m, x)==true) return m; 6 if(g(m, x)==true) {//find left side: [l, m) 7 r = m; 8 } else {//find right side: [m+1, r) 9 l = m+1; 10 } 11 } 12 return l; 13 }
f(m,x)可选(可有可无)
若f(m,x)存在,则返回完全满足f(m,x)的index。
若f(m,x)不存在,则找到第一个满足g(m,x)的数。
- lower_bound : (左闭<第一个满足>) Find first index i, such that A[i] >= x
1 int lower_bound(int l, int r, int x) { 2 // range: [l,r) 3 while(l<r) { 4 int m = l+(r-l)/2; 5 if(m >= x) {//find first val which >=x 6 r = m; 7 } else { 8 l = m+1; 9 } 10 } 11 return l; 12 }
- upper_bound : (右开<第一个不满足>) Find first index i, such that A[i] > x
1 int upper_bound(int l, int r, int x) { 2 // range: [l,r) 3 while(l<r) { 4 int m = l+(r-l)/2; 5 if(m > x) {//find first val which >x 6 r = m; 7 } else { 8 l = m+1; 9 } 10 } 11 return l; 12 }
同样的,本问题,查找,第一个val,使得val^2>x
然后res=val-1,即是所求,最大取整的,满足res^2<=x的数。
代码参考:
1 class Solution { 2 public: 3 int mySqrt(int x) { 4 int right=INT_MAX; 5 int left=1; 6 if(x==0)return 0; 7 while(left<right){ 8 int mid = left+(right-left)/2; 9 if((long long)mid*mid > x){ 10 right = mid; 11 }else{ 12 left = mid+1; 13 } 14 } 15 return left-1; 16 } 17 };