leedcode 69 Sqrt(x)

本文介绍了一种使用二分法查找整数平方根的方法。通过不断缩小搜索范围,最终找到最接近目标值的整数平方根。文章提供了一个Python实现的例子。

 

69Sqrt(x)    28.60%开方,用二分法缩小尝试范围

 

#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Wed Feb  7 16:06:06 2018

@author: vicky
"""
##import math
#
#class Solution:
#    def mySqrt(self, x):
#        """
#        :type x: int
#        :rtype: int
#        """
#        #return int(math.sqrt(x))
#        
#        #时间超过了
#        for n in range(int(x/4)+4):
#            if n**2>x:
#                return n-1
#                break
#            elif n**2==x:
#                return n
#                break

#https://www.cnblogs.com/grandyang/p/4346413.html
#法一:二分搜索法: http://www.cnblogs.com/luoxn28/p/5767571.html
#            将查找的键和子数组的中间键作比较,
#            如果被查找的键小于中间键,就在左子数组继续查找;
#            如果大于中间键,就在右子数组中查找,
#            否则中间键就是要找的元素。
class Solution:
    def mySqrt(self, x):
        """
        :type x: int
        :rtype: int
        """
        left=0
        right=int(x/2)+1
        while left<=right:
            mid=int((left+right)/2)
            if mid**2<x: #向左子数组继续查找
                if (mid+1)**2>x:
                    return mid
                left=mid+1 #注意是mid+1不是left+1,直接把mid左边的区间不要
            elif mid**2==x:
                return mid
            else:         #向右子数组继续查找
                right=mid-1 #注意是mid+1不是right-1,直接把mid右边的区间不要
#        return left-1


##法二:牛顿迭代法,要求f(x)=0解,用x[n+1]=x[n]-f(x[n])/f'(x[n])来迭代
##  这里f(x)=x^2-n,则x[n+1]=x[n]-{x[n]^2-n}/{2x[n]}={x[n]+n/x[n]}/2
#
##  当x=5、7...等时有bug,迭代不出来
#class Solution:
#    def mySqrt(self, x):
#        """
#        :type x: int
#        :rtype: int
#        """
#        r=x
#        while r*r>x:
#            r=(r+x/r)/2
#        return int(r)

x=0
print(Solution().mySqrt(x))

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值