【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 Sqrt(x)LeetCode
- Leetcode-Sqrt(x)LeetCode
- leetcode-69. Sqrt(x)LeetCode
- Sqrt(int x) leetcode javaLeetCodeJava
- LeetCode 第 69 題 (Sqrt(x))LeetCode
- 【Lintcode】1728. X of a Kind in a Deck of Cards
- JavaScript Math.sqrt()JavaScript
- sqrt-data-structureStruct
- JavaScript Math.SQRT2JavaScript
- 141. 環形連結串列
- JavaScript Math.SQRT1_2JavaScript
- 【Leetcode】141. Linked List CycleLeetCode
- 淺談 BigInteger.Sqrt 方法
- 演算法141. 環形連結串列演算法
- [LintCode] Daily TemperaturesAI
- LintCode 子樹
- LintCode-Backpack
- LintCode-HeapifyAPI
- 詳解MySQL中的SQRT函式的使用方法MySql函式
- [LintCode] Permutation in String
- LintCode 主元素 II
- LintCode 解碼方法
- LintCode-Search for a Range
- LintCode-K Sum
- LintCode-Word SegmentationSegmentation
- LintCode-Hash FunctionFunction
- LintCode-Fast PowerAST
- Lintcode-Max Tree
- LintCode-Partition Array
- LintCode-Subarray Sum
- LintCode-Majority Number
- LintCode-A+B Problem
- LintCode-BackPack II
- LintCode-Previous Permuation
- LintCode 字串比較字串
- scheme 求平方根函式 sqrt 牛頓法實現Scheme函式
- [LintCode] 3Sum Smaller
- 【Lintcode】572. Music PairsAI