May LeetCoding Challenge9 之 求方差
Posted yawenw
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了May LeetCoding Challenge9 之 求方差相关的知识,希望对你有一定的参考价值。
两种解法:
1.单独判断1,二分法在范围[2,num/2]搜索,如果平方与num相等,则返回true
2.牛顿法
JAVA
class Solution { public boolean isPerfectSquare(int num) { if(num == 1) return true; long left = 2; long right = num/2; while(left <= right){ long mid = left + (right-left)/2; if(mid*mid == num) return true; if(mid*mid > num) right = mid-1; else left = mid+1; } return false; } }
class Solution { public boolean isPerfectSquare(int num) { if (num < 2) return true; long x = num / 2; while (x * x > num) { x = (x + num / x) / 2; } return (x * x == num); } }
Python3
class Solution: def isPerfectSquare(self, num: int) -> bool: if num == 1: return True left = 2 right = num//2 while left <= right: mid = left + (right-left)//2 if mid*mid == num: return True if mid*mid > num: right = mid - 1 else: left = mid + 1 return False
class Solution: def isPerfectSquare(self, num: int) -> bool: if num < 2: return True x = num // 2 while x * x > num: x = (x + num // x) // 2 return x * x == num
以上是关于May LeetCoding Challenge9 之 求方差的主要内容,如果未能解决你的问题,请参考以下文章
May LeetCoding Challenge8 之 交叉相乘
May LeetCoding Challenge8 之 交叉相乘
May LeetCoding Challenge 之 标准二分查找法
May LeetCoding Challenge27 之 二分图