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.
複製代碼
實現int sqrt(int x)。 計算並返回x的平方根,其中x保證是一個非負整數。 因爲返回類型是整數,所以將截斷小數,只返回結果的整數部分。 示例1: 輸入:4 輸出:2 示例2: 輸入:8 輸出:2 說明:8的平方根是2.82842…,自 小數部分被截斷,返回2。java
本題是找一個數是當前數的平方根,若是是小數,則返回捨棄小數的值。咱們能夠用遍歷的方式,來判斷是否是,當時這邊須要考慮一下越界的問題,其實也能夠不關注,畢竟能夠得出越界的上限的平方根是多少,就能夠避免這個問題。除了遍歷,咱們也能夠用java自帶的Math類來解決,是最簡單的。除此以外,本題是找值,並且是在特定範圍內找一個值,就能夠想到是否能夠用二分法來簡短查詢時間。git
按照咱們的思路來編輯,代碼以下bash
if (x <= 0) {
return 0;
}
for (int i =x/2+1; i>=0; i=i/2) {
long result = 1L*i * i;
if (result == x) {
return i;
}
if (result > x) {
return i - 1;
}
}
return 0;
複製代碼
時間複雜度: 該方案用了循環m因此f(n)=(n/2)=n;因此O(f(n))=O(n/2),即T(n)=O(n)ui
空間複雜度: 該方案使用了沒有使用額外空間,因此空間複雜度是O(n)=O(1);spa
使用二分法,代碼以下翻譯
if (x <= 0) {
return 0;
}
int start = 0;
int end = x;
while (start <= end) {
int index = (start + end) / 2;
long sum = 1L * index * index;
if (sum > x) {
end = index - 1;
} else {
start = index + 1;
}
}
return end;
複製代碼
時間複雜度: 該方案用了循環m因此f(n)=(logn)=n;因此O(f(n))=O(logn),即T(n)=O(logn)code
空間複雜度: 該方案使用了沒有使用額外空間,因此空間複雜度是O(n)=O(1);ci
借用Math類,代碼以下it
if (x <= 0) {
return 0;
}
return (int)Math.sqrt(x);
複製代碼
時間複雜度: 該方案用了循環m因此f(n)=(1)=n;因此O(f(n))=O(1),即T(n)=O(1)io
空間複雜度: 該方案使用了沒有使用額外空間,因此空間複雜度是O(n)=O(1);
本題的大體解法如上所訴, 在特意範圍內,並且仍是有序的,咱們天然能夠想到二分法來簡化遍歷,因爲這題是須要最近的最小值,因此當end--後,大的值就變成來最小值,剛恰好知足。