【LeetCode】69. Sqrt(x) 解题报告(Python & C++)
作者: 负雪明烛
id: fuxuemingzhu
个人博客: http://fuxuemingzhu.cn/
题目地址:https://leetcode.com/problems/sqrtx/description/
题目描述
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.
题目大意
求x的算术平方根向下取整。
解题方法
方法一:库函数
求算数平方根。可以直接用库。
import math
class Solution(object):
def mySqrt(self, x):
"""
:type x: int
:rtype: int
"""
return int(math.sqrt(x))
方法二:牛顿法
牛顿法详见:https://en.wikipedia.org/wiki/Newton%27s_method
这个问题其实就是求f(x)=num - x ^ 2的零点。
那么,Xn+1 = Xn - f(Xn)/f'(Xn).
又f'(x) = -2x.
得Xn+1 = Xn +(num - Xn ^ 2)/2Xn = (num + Xn ^ 2) / 2Xn = (num / Xn + Xn) / 2.
即t = (num / t + t) / 2.
class Solution(object):
def mySqrt(self, x):
"""
:type x: int
:rtype: int
"""
num = x
while num * num > x:
num = (num + x / num) / 2
return num
方法三:二分查找
这个题是二分查找的经典题目了,直接套用二分查找的模板即可。这里贡献一个二分查找的模板,模板中查找的区间是[l, r),即左闭右开。
def binary_searche(l, r):
while l < r:
m = l + (r - l) // 2
if f(m): # 判断找了没有,optional
return m
if g(m):
r = m # new range [l, m)
else:
l = m + 1 # new range [m+1, r)
return l # or not found
这个题的二分查找版本的代码如下:
class Solution(object):
def mySqrt(self, x):
"""
:type x: int
:rtype: int
"""
left, right = 0, x + 1
# [left, right)
while left < right:
mid = left + (right - left) // 2
if mid ** 2 == x:
return mid
if mid ** 2 < x:
left = mid + 1
else:
right = mid
return left - 1
二刷的时候用了二分查找,但是写法和上面略有区别。
class Solution(object):
def mySqrt(self, x):
"""
:type x: int
:rtype: int
"""
left, right = 0, x + 1 #[left, right)
while left < right:
mid = (left + right) // 2
if mid ** 2 == x:
return mid
elif (mid - 1) ** 2 < x and mid ** 2 >= x:
return mid - 1
elif mid ** 2 < x:
left = mid + 1
else:
right = mid
return left
如果是C++就比较痛苦了,因为要考虑到数字是不是越界了,所以我用了long long.
class Solution {
public:
int mySqrt(long long x) {
if (x == 0) return 0;
long long left = 0, right = x + 1; //[left, right)
while (left < right) {
long long mid = left + (right - left) / 2;
if (mid == x / mid) {
return mid;
} else if (mid < x / mid) {
left = mid + 1;
} else {
right = mid;
}
}
return left - 1;
}
};
如果只使用int的话,需要考虑right = x + 1这一步可能会超边界,所以仍然使用[left,right)区间,那么当x<=1的时候,返回的应该是x。
class Solution {
public:
int mySqrt(int x) {
if (x <= 1) return x;
int left = 0, right = x; //[left, right)
while (left < right) {
int mid = left + (right - left) / 2;
if (mid == x / mid) {
return mid;
} else if (mid < x / mid) {
left = mid + 1;
} else {
right = mid;
}
}
return left - 1;
}
};
日期
2018 年 2 月 4 日
2018 年 10 月 26 日 ——项目验收结束了!
2018 年 11 月 27 日 —— 最近的雾霾太可怕
【LeetCode】69. Sqrt(x) 解题报告(Python & C++)的更多相关文章
- C++版 - Leetcode 69. Sqrt(x) 解题报告【C库函数sqrt(x)模拟-求平方根】
69. Sqrt(x) Total Accepted: 93296 Total Submissions: 368340 Difficulty: Medium 提交网址: https://leetcod ...
- 【LeetCode】120. Triangle 解题报告(Python)
[LeetCode]120. Triangle 解题报告(Python) 作者: 负雪明烛 id: fuxuemingzhu 个人博客: http://fuxuemingzhu.cn/ 题目地址htt ...
- LeetCode 1 Two Sum 解题报告
LeetCode 1 Two Sum 解题报告 偶然间听见leetcode这个平台,这里面题量也不是很多200多题,打算平时有空在研究生期间就刷完,跟跟多的练习算法的人进行交流思想,一定的ACM算法积 ...
- 【LeetCode】Permutations II 解题报告
[题目] Given a collection of numbers that might contain duplicates, return all possible unique permuta ...
- Leetcode 69. Sqrt(x)及其扩展(有/无精度、二分法、牛顿法)详解
Leetcode 69. Sqrt(x) Easy https://leetcode.com/problems/sqrtx/ Implement int sqrt(int x). Compute an ...
- 【LeetCode】Island Perimeter 解题报告
[LeetCode]Island Perimeter 解题报告 [LeetCode] https://leetcode.com/problems/island-perimeter/ Total Acc ...
- 【LeetCode】01 Matrix 解题报告
[LeetCode]01 Matrix 解题报告 标签(空格分隔): LeetCode 题目地址:https://leetcode.com/problems/01-matrix/#/descripti ...
- 【LeetCode】Largest Number 解题报告
[LeetCode]Largest Number 解题报告 标签(空格分隔): LeetCode 题目地址:https://leetcode.com/problems/largest-number/# ...
- 【LeetCode】Gas Station 解题报告
[LeetCode]Gas Station 解题报告 标签(空格分隔): LeetCode 题目地址:https://leetcode.com/problems/gas-station/#/descr ...
随机推荐
- C语言之内核中的struct list_head 结构体
以下地址文章解释很好 http://blog.chinaunix.net/uid-27122224-id-3277511.html 对下面的结构体分析 1 struct person 2 { 3 in ...
- C语言中的指针的小标可以是负数
首先,创建一个正常的数组 int A[20];.然后用指针指向其中间的元素 int *A2 = &(A[10]); 这样,A2[-10 ... 9] 就是一个可用的有效范围了. 1 2 3 4 ...
- 静态库动态库的编译、链接, binutils工具集, 代码段\数据段\bss段解释
#1. 如何使用静态库 制作静态库 (1)gcc *.c -c -I../include得到o文件 (2) ar rcs libMyTest.a *.o 将所有.o文件打包为静态库,r将文件插入静态库 ...
- 数组相关API,reduce
reduce() 方法接受一个数组作为输入值并返回一个值.这点挺有趣的.reduce 接受一个回调函数,回调函数参数包括一个累计器(数组每一段的累加值,它会像雪球一样增长),当前值,和索引.reduc ...
- 【Python】【Basic】MacOS上搭建Python开发环境
1. Python3 1.1. 下载地址:https://www.python.org/downloads/mac-osx/ 1.1.1. PKG包安装: 没啥可说的,点点点,下一步而已,不用手动配置 ...
- Output of C++ Program | Set 6
Predict the output of below C++ programs. Question 1 1 #include<iostream> 2 3 using namespace ...
- Linux:cut命令...未完待续
一.定义 正如其名,cut的工作就是"剪",具体的说就是在文件中负责剪切数据用的.cut是以每一行为一个处理对象的,这种机制和sed是一样的. 2.剪切依据 cut命令主要是接受三 ...
- 【Linux】【Commands】文本查看类
分屏查看命令:more和less more命令: more FILE 特点:翻屏至文件尾部后自动退出: less命令: less FILE head命令: 查看文件的前n行: head [option ...
- Spring Boot的异步任务、定时任务和邮件任务
一.异步任务 1.启动类添加注解@EnableAsync,开启异步任务注解功能: 2.需要异步执行的方法上添加@Async注解. 二.定时任务 1.启动类添加注解@EnableScheduling,开 ...
- 【Matlab】向图像域添加噪声/高斯/均匀/伽马/指数/椒盐
[向图像域添加噪声] matlab自带一个函数:imnoise,可以对图像添加噪声. Matlab的说明 https://www.mathworks.com/help/images/ref/imnoi ...