367. 有效的完全平方数
方法一:优先考虑到暴力破解
这有什么好犹豫的,直接从1的平方、2的平方、3的平方、、、
当某个数x的平方等于输入参数,返回true;
当某个数y的平方大于输入参数,跳出循环返回false;
var isPerfectSquare = function(num) {
let index = 0;
let res = false
while(num >= index*index){
if(num == index*index){
res = true
}
index++
}
return res
};
方法二:二分法
有序数据,严格递增;妥妥二分查找呀;
老套路:定义左侧最小值,定义右侧做大值,最大值当然就是输入参数;
找到最小值最大值的中间值,中间值平方是否等于入参;
等于入参返回true;
小于入参将中间值赋值给左侧最小值;
大于入参将中间值赋值给右侧最大值;
代码如下:
var isPerfectSquare = function(num) {
if(num === 1) return true;
let left = 1;
let right = num;
while(left < right){
const mid = Math.floor(left + (right-left)/2);
const t = mid * mid
if(t === num){
return true
}else if(t < num){
left = mid+1
}else{
right = mid
}
}
return false
};