作者: 负雪明烛
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++)的更多相关文章

  1. C++版 - Leetcode 69. Sqrt(x) 解题报告【C库函数sqrt(x)模拟-求平方根】

    69. Sqrt(x) Total Accepted: 93296 Total Submissions: 368340 Difficulty: Medium 提交网址: https://leetcod ...

  2. 【LeetCode】120. Triangle 解题报告(Python)

    [LeetCode]120. Triangle 解题报告(Python) 作者: 负雪明烛 id: fuxuemingzhu 个人博客: http://fuxuemingzhu.cn/ 题目地址htt ...

  3. LeetCode 1 Two Sum 解题报告

    LeetCode 1 Two Sum 解题报告 偶然间听见leetcode这个平台,这里面题量也不是很多200多题,打算平时有空在研究生期间就刷完,跟跟多的练习算法的人进行交流思想,一定的ACM算法积 ...

  4. 【LeetCode】Permutations II 解题报告

    [题目] Given a collection of numbers that might contain duplicates, return all possible unique permuta ...

  5. Leetcode 69. Sqrt(x)及其扩展(有/无精度、二分法、牛顿法)详解

    Leetcode 69. Sqrt(x) Easy https://leetcode.com/problems/sqrtx/ Implement int sqrt(int x). Compute an ...

  6. 【LeetCode】Island Perimeter 解题报告

    [LeetCode]Island Perimeter 解题报告 [LeetCode] https://leetcode.com/problems/island-perimeter/ Total Acc ...

  7. 【LeetCode】01 Matrix 解题报告

    [LeetCode]01 Matrix 解题报告 标签(空格分隔): LeetCode 题目地址:https://leetcode.com/problems/01-matrix/#/descripti ...

  8. 【LeetCode】Largest Number 解题报告

    [LeetCode]Largest Number 解题报告 标签(空格分隔): LeetCode 题目地址:https://leetcode.com/problems/largest-number/# ...

  9. 【LeetCode】Gas Station 解题报告

    [LeetCode]Gas Station 解题报告 标签(空格分隔): LeetCode 题目地址:https://leetcode.com/problems/gas-station/#/descr ...

随机推荐

  1. cat的生产应用

    web日志文件的合并 cat one.log two.log >all.log sort -k 4 all.log   按照第四列进行时间排序

  2. PhantomJS的安装和使用

    PhantomJS是一个无界面的.可脚本编程的WebKit浏览器引擎,它原生支持多种Web标准:DOM操作.CSS选择器.JSON.Canvas以及SVG.Selenium支持PhantomJS,这样 ...

  3. Volatile的3大特性

    Volatile volatile是Java虚拟机提供的轻量级的同步机制 3大特性 1.保证可见性 当多个线程同时访问同一个变量时,一个线程修改了这个变量的值,其他线程能够立即看得到修改的值 案例代码 ...

  4. hbase调优

    @ 目录 一.phoenix调优 1.建立索引超时,查询超时 2.预分区 hbase shell预分区 phoenix预分区 3.在创建表的时候指定salting. 4.二级索引 建立行键与列值的映射 ...

  5. 05 Windows安装python3.6.4+pycharm环境

    windows安装python3.6.4环境 使用微信扫码关注微信公众号,并回复:"Python工具包",免费获取下载链接! 一.卸载python环境 卸载以下软件: 二.安装py ...

  6. javaWeb - 2 — ajax、json — 最后附:后台获取前端中的input type = "file"中的信息 — 更新完毕

    1.ajax是什么? 面向百度百科一下就知道了,这里就简单提炼一下 Ajax即Asynchronous Javascript And XML(异步JavaScript和XML).当然其实我们学的应该叫 ...

  7. 淘宝、网易移动端 px 转换 rem 原理,Vue-cli 实现 px 转换 rem

       在过去的一段时间里面一直在使用Vue配合 lib-flexible和px2rem-loader配合做移动端的网页适配.秉着求知的思想,今天决定对他的原理进行分析.目前网上比较主流使用的就是淘宝方 ...

  8. 【编程思想】【设计模式】【创建模式creational】Pool

    Python版 https://github.com/faif/python-patterns/blob/master/creational/pool.py #!/usr/bin/env python ...

  9. 使用JDBCTemplate执行DQL/DML语句

    package cn.itcast.datasource.jdbctemplate;import cn.itcast.domain.User;import cn.itcast.utils.JDBCUt ...

  10. JSP中session、cookie和application的使用

    一.session (单用户使用) 1.用处:注册成功后自动登录,登录后记住用户状态等 使用会话对象session实现,一次会话就是一次浏览器和服务器之间的通话,会话可以在多次请求中保存和使用数据. ...