【Lintcode】141. Sqrt(x)
題目地址:
https://www.lintcode.com/problem/sqrtx/description
給定一個非負整數 n n n,返回最大的滿足 x 2 ≤ n x^2\le n x2≤n的 x x x。
直接二分。程式碼如下:
public class Solution {
/**
* @param x: An integer
* @return: The sqrt of x
*/
public int sqrt(int x) {
// write your code here
long l = 0, r = x;
while (l < r) {
long m = l + (r - l + 1 >> 1);
if (m <= x / m) {
l = m;
} else {
r = m - 1;
}
}
return (int) l;
}
}
時間複雜度 O ( log n ) O(\log n) O(logn),空間 O ( 1 ) O(1) O(1)。
相關文章
- leetcode-69. Sqrt(x)LeetCode
- 【Lintcode】1728. X of a Kind in a Deck of Cards
- JavaScript Math.sqrt()JavaScript
- sqrt-data-structureStruct
- 141. 環形連結串列
- JavaScript Math.SQRT2JavaScript
- JavaScript Math.SQRT1_2JavaScript
- 演算法141. 環形連結串列演算法
- [LintCode] Daily TemperaturesAI
- [LintCode] Permutation in String
- [LintCode/LeetCode] Meeting RoomsLeetCodeOOM
- Lintcode 1263. Is Subsequence
- 【Lintcode】1189. Minesweeper
- 【Ynoi 2019 模擬賽】Yuno loves sqrt technology III
- [LeetCode/LintCode] Largest Palindrome ProductLeetCode
- [LintCode/LeetCode] Contains Duplicate IIILeetCodeAI
- [LintCode] Check Full Binary Tree
- [LintCode/LeetCode] Remove Duplicate LettersLeetCodeREM
- [LintCode] 3Sum Smaller
- 【Lintcode】1615. The Result of Investment
- [LintCode] Binary Tree Level Order
- 【Lintcode】1736. Throw Garbage
- 【Lintcode】1665. Calculate Number
- 【Lintcode】1789. Distinguish UsernameNGUI
- 【Lintcode】1562. Number of RestaurantsREST
- 【Lintcode】576. Split Array
- 【Lintcode】1267. Lexicographical Numbers
- 【Lintcode】1415. Residual Product
- 【Lintcode】1230. Assign CookiesCookie
- 【Lintcode】1732. Snakes and Ladders
- 【Lintcode】1218. Number Complement
- 【Lintcode】1850. Pick ApplesAPP
- 【Lintcode】572. Music PairsAI
- 【Lintcode】318. Character Grid
- 【Lintcode】1891. Travel Plan
- 詳解MySQL中的SQRT函式的使用方法MySql函式
- [LintCode/LeetCode] Check Sum of K PrimesLeetCode
- [LintCode]NumberofIslands(島嶼個數)