【一次过】Lint code: 697. Sum of Square Numbers

本文介绍了一种算法,用于判断一个给定的整数是否可以表示为两个整数的平方和。提供了两种解题思路,一种是常规的双层遍历方法,时间复杂度为O(N^2);另一种是优化后的单次遍历方法,时间复杂度降低到O(N),通过计算并检查剩余部分的平方根是否为整数来判断。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

给一个整数 c, 你需要判断是否存在两个整数 a 和 b 使得 a^2 + b^2 = c.

样例

给出 n = 5
返回 true // 1 * 1 + 2 * 2 = 5
给出 n = -5
返回 false


解题思路1:

常规思路,两轮遍历,时间复杂度O(N^2)

public class Solution {
    /**
     * @param num: the given number
     * @return: whether whether there're two integers
     */
    public boolean checkSumOfSquareNumbers(int num) {
        // write your code here
        if(num < 0)
            return false;

        for(int i=0; i<=(int)Math.sqrt(num); i++){
            for(int j=0; j<=(int)Math.sqrt(num); j++){
                if(i*i + j*j == num)
                    return true;
            }
        }
        
        return false;
    }
}

解题思路2:

还有一种方法,只需遍历一次,原题可变形为j*j=num-i*i,i作为遍历对象,计算出的j如果开根号后是整数,则是ok的。

时间复杂度O(N)

public class Solution {
    /**
     * @param num: the given number
     * @return: whether whether there're two integers
     */
    public boolean checkSumOfSquareNumbers(int num) {
        // write your code here
        if(num < 0)
            return false;

        for(int i=0; i<=Math.sqrt(num); i++){
            int temp = num - i*i;
            
            if(Math.sqrt(temp) == (int)Math.sqrt(temp))
                return true;
        }
        
        return false;
    }
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值