1. 程式人生 > >LeetCode 69 _ Sqrt(x) 求平方根 (Easy)

LeetCode 69 _ Sqrt(x) 求平方根 (Easy)

提交 快速 mem 縮小 題目 implement span nat turned

Description:

Implement int sqrt(int x).

Compute and return the square root of x, where x is guaranteed to be a non-negative integer.

Since the return type is an integer, the decimal digits are truncated and only the integer part of the result is returned.

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.

Solution:

這道題讓我們求x的平方根

看到這種根據大數求與它相關的小數的值,大多都是二分法啦。二分法是最快速的方法。

大致思想就是設定兩個指針分別在兩側,看看結果是在左半部分還是右半部分,如果在左半部分則將右側指針移至中間,繼續搜索左半部分;另一半情況亦然。

二分法這種類型的題目,最後都是將範圍不斷縮小,循環判斷的條件就是左指針必須在右指針左側,否則則循環結束。

這種題有一點需要註意的時,找終點的時候一定要是將“left+(right - left)/2”,千萬不可以直接簡單的寫“(right - left)/2”!!

另外這道題還需要留意越界的問題,將結果盡量保持在小的範圍,否則就報錯咯!!

Code:

public int mySqrt(int x) {
    int left = 0, right = x;
    if (x <= 1){
    	return x;
    }
    while (left < right){
    	int mid = left + (right - left)/2;
    	// mid寫左半以免越界!
    	if (x / mid >= mid){ // 如果x大於mid^2,證明mid太小,要取右半
    		left = mid + 1; // 如果x剛好等於^2,也將其+1,便於之後取-1的結果 
    	}else{
    		right = mid;     // 如果x小於mid^2,證明mid太大,要取左半
    	}
    }
    return right-1;
}

  

提交情況:

Runtime: 1 ms, faster than 100.00% of Java online submissions for Sqrt(x).
Memory Usage: 32.3 MB, less than 100.00% of Java online submissions for Sqrt(x).

LeetCode 69 _ Sqrt(x) 求平方根 (Easy)