Implement int sqrt(int x) .
Compute and return the square root of x.
<Solution>這題有兩種解法,一種是二分法,一種是牛頓法 (資料1, 資料2)
這邊使用牛頓法來處理
xi+1=xi - (xi2 - n) / (2xi) = xi - xi / 2 + n / (2xi) = xi / 2 + n / 2xi = (xi + n/xi) / 2
code 如下
c++
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Solution { | |
public: | |
int mySqrt(int x) { | |
if(x == 0) { | |
return 0; | |
} | |
double ans = 1.0, prv = 0; | |
while(ans != prv) { | |
prv = ans; | |
ans = (ans + x / ans) / 2; | |
} | |
return static_cast<int>(ans); | |
} | |
}; |
還有另一種不需要被數學公式的解法
在 1 到 x 之間,使用 binary search 來找
kotlin,time complexity = O(logN)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Solution { | |
fun mySqrt(x: Int): Int { | |
return if(x == 0) { | |
0 | |
} else { | |
var left = 1 | |
var right = x | |
var mid = 0 | |
while(left < right) { | |
mid = left + (right - left) / 2 | |
when { | |
mid <= x / mid && (mid+1) > x / (mid+1) -> return mid | |
mid > x / mid -> right = mid | |
else -> left = mid + 1 | |
} | |
} | |
return left | |
} | |
} | |
} |
沒有留言:
張貼留言