close
69. Sqrt(x)
Implement int sqrt(int x)
.
Compute and return the square root of x.
x is guaranteed to be a non-negative integer.
Example 1:
Input: 4 Output: 2
Example 2:
Input: 8 Output: 2 Explanation: The square root of 8 is 2.82842..., and since we want to return an integer, the decimal part will be truncated.
這題我只想到暴力解,所以就直接放棄看解答了,解法非常有趣
用BFS,不斷逼近正確的區段,因為有可能不是整數,最後確定數值是用 if(mid+1 > x/(mid+1)) 來判斷 (來確定下個值會過大,正解就是這個值)
class Solution { public int mySqrt(int x) { int l=1, r=(int)Math.ceil(x/2.0); while(l <= r) { int mid = l+(r-l)/2; if(mid > x/mid) r = mid-1; else { if((mid+1) > x/(mid+1)) return mid; l=mid+1; } } return 0; } }
全站熱搜