边工作边刷题: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