边工作边刷题:70天一遍leetcode: day 42

Valid Perfect Square

要点:binary search的题,可以扩展到double,就变成<=的情况了
错误点:

  • 2以上的情况n/2,但是<2就可能n/2+1。所以high是n/2+1

class Solution(object):
    def isPerfectSquare(self, num):
        """
        :type num: int
        :rtype: bool
        """
        low, high = 1, num//2+1
        while low<=high:
            mid = low + (high-low)/2
            if mid*mid==num:
                return True
            elif mid*mid<num:
                low=mid+1
            else:
                high=mid-1
        return False
        
posted @ 2016-07-04 03:51  absolute100  阅读(84)  评论(0编辑  收藏  举报