边工作边刷题:70天一遍leetcode: day 26-1

Sqrt(x)

要点:binary search很容易想,注意corner cases:如果>=2,high的初始值为x/2,所以对x=0 or x=1特殊处理,否则设定x为high初始值会TLE

class Solution(object):
    def mySqrt(self, x):
        """
        :type x: int
        :rtype: int
        """
        if x==0: return 0
        if x==1: return 1
        low,high = 0,x/2
        m = 0
        while low<=high:
            m = low + (high-low)/2
            if m*m<=x and (m+1)*(m+1)>x:
                return m
            if m*m<x:
                low = m+1
            else:
                high = m-1
                
        return m
posted @ 2016-04-22 10:47  absolute100  阅读(68)  评论(0编辑  收藏  举报