LeetCode-Sum of Square Numbers

本文探讨了给定非负整数c,是否存在两个整数a和b,满足a²+b²=c的问题。通过两种方法解决:一是暴力求解,二是利用二分查找优化搜索过程。

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

Description:
Given a non-negative integer c, your task is to decide whether there’re two integers a and b such that a2 + b2 = c.

Example 1:

Input: 5
Output: True
Explanation: 1 * 1 + 2 * 2 = 5

Example 2:

Input: 3
Output: False

题意:给定一个非负数ccc,计算是否存在整数aaabbb,使得a2+b2=ca^2 + b^2 = ca2+b2=c

解法一(超时):最简单的办法就是使用暴力求解,aaabbb的取值区间在[0,c1/2][0, c^{1/2}][0,c1/2];最终肯定会超时的;

Java
class Solution {
    public boolean judgeSquareSum(int c) {
        for (long a = 0; a * a <= c; a++) {
            for (long b = 0; b * b <= c; b++) {
                if (a * a + b * b == c) {
                    return true;
                }
            }
        }
        return false;
    }
}

解法二:对公式变形得到b2=c−a2b^2 = c - a^2b2=ca2,因此我们只需要在区间[0,c1/2][0, c^{1/2}][0,c1/2]内寻找是否由满足条件的bbb即可;这里我们利用二分查找来实现快速的查找;

Java
class Solution {
    public boolean judgeSquareSum(int c) {
        for (long a = 0; a * a <= c; a++) {
            long b = c - a * a;
            if (find(0, b, b)) {
                return true;
            }
        }
        return false;
    }
    
    private boolean find(long low, long high, long target) {
        if (low > high) {
            return false;
        }
        while (low <= high) {
            long mid = low + (high - low) / 2;
            if (mid * mid == target) {
                return true;
            } else if (mid * mid > target) {
                high = mid - 1;
            } else {
                low = mid + 1;
            }
        }
        return false;
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值