1. 程式人生 > >LeetCode 69. Sqrt(x)

LeetCode 69. Sqrt(x)

nbsp part 要求 tput http ret 實現 ati div

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.



要求編程實現sqrt()函數,比較高效的方法是使用二分搜索,不難證明,對於一個整數n,其平方根所在的範圍為[0,n/2+1],所以需要在此區間內進行二分查找,代碼如下
 1 class Solution {
 2 public:
 3     int mySqrt(int x) {
 4         long long i = 0, j = x / 2 + 1;
 5         while(i <= j)
 6         {
 7             long long mid = (i + j) / 2;
 8             long long sq = mid * mid;
9 if (sq == x) 10 return mid; 11 else if (sq < x) 12 i = mid + 1; 13 else 14 j = mid - 1; 15 } 16 return j; 17 } 18 };

時間復雜度:O(logn)

空間復雜度:O(1)

當然也可以用牛頓下降法求解,詳細請移步:

http://www.cnblogs.com/AnnieKim/archive/2013/04/18/3028607.html

http://www.cnblogs.com/grandyang/p/4346413.html

一刷:各種出錯,首先要註意使用long long類型,否則會溢出;其次是要註意返回 j 而不是 i ,以為當平方根不為整數,需要舍棄小數部分,也就是向下取整

 

LeetCode 69. Sqrt(x)