LeetCode—有效的完全平方数(二分)

有效的完全平方数(简单)

2020年6月21日

题目来源:力扣

在这里插入图片描述

解题
题目规定不能用sqrt(),那想到的肯定是遍历了,从1遍历到这个数,看看中间有没有一个数的平方值是它

大体思路确定了,遍历需要优化。

首先左边界很明确应该是1,右边界可以用这个num/2,这个思想在写计算质数的时候就应该很清晰了。

确定了一个范围之后,也不能傻傻的从头遍历到尾。用二分法来快速查找,精准定位。

这里注意数的平方不要用i*i这种方式,用Math.pow(i,2),不然会超时

class Solution {
    public boolean isPerfectSquare(int num) {
        int l=1;
        int r=num/2+1;
        while(l<=r){
            int c=(l+r)/2;
            if(Math.pow(c,2)==num) return true;
            else if(Math.pow(c,2)<num) l=c+1;
            else r=c-1;
        }
        return false || num==1;
    }
}

在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/weixin_41541562/article/details/106882309
今日推荐