平方数之和

Sum of Square Numbers

Given a non-negative integer c, decide whether there’s two integers a and b such that a^2 + b^2 = c.

Example 1:

Input: c = 5

Output: true

Explanation: 1 * 1 + 2 * 2 = 5

Example 2:

Input: c = 3

Output: false

Example 3:

Input: c = 4

Output: true

Example 4:

Input: c = 2

Output: true

Example 5:

Input: c = 1

Output: true

Constraints:

  • 0 <= c <= 2^31-1

今天的题目是判断一个非负整数是否是两个整数的平方和。要求输入一个整数,如果它是某两个整数的平方和,就返回true,否则返回false。题目看起来比较简单,也没有太多的约束。

  • 方法一:遍历

    ​ 首先我想到的第一个办法就是最简单的——遍历。不过没有必要遍历所有的数,那样消耗的时间太多了,可以稍作一些优化。

    ​ 我们不需要从0开始遍历到c,只需要遍历到sqrt©即可,因为再大的话其中一个数就比c大了,不可能出现两个数的平方和等于c的情况。

    ​ 所以我们写出的算法如下:

    ​ 用一个整数i从0开始遍历到sqrt©向下取整,如果sqrt(c-i*i)的值是一个整数,那就说明c是两个整数的平方和,返回true。如果一直到遍历完所有可能的值都没有找到满足条件的数,则返回false。实现的代码如下:

    /**
     * @author: LittleWang
     * @date: 2021/4/28
     * @description:
     */
    public class Solution {
        public boolean judgeSquareSum(int c) {
            for (int i = 0; i <= Math.sqrt(c); i++) {
                double temp = Math.sqrt(c - i*i);
                if(temp == (int)temp)
                    return true;
            }
            return false;
        }
    }
    
    

    结果没有问题,只是用时有点多

在这里插入图片描述

  • 方法二:双指针法

    我们还可以定义左右两个指针,left指针从0开始,right指针从sqrt©开始,判断left*left+right*right与c的大小关系,根据它们之间的关系调整左右指针的值

    • left*left+right*right == c:返回true
    • left*left+right*right > c:右指针–
    • left*left+right*right < c:左指针++

    直到left==right时,如果还没有找到使left*left+right*right == c的值,则返回false

    代码如下:

    /**
     * @author: LittleWang
     * @date: 2021/4/28
     * @description:
     */
    public class Solution2 {
        public boolean judgeSquareSum(int c) {
            int left = 0, right = (int)Math.sqrt(c);
            while(left <= right) {
                int sum = left*left + right*right;
                if(sum == c)
                    return true;
                else if(sum < c)
                    left++;
                else
                    right--;
            }
            return false;
        }
    }
    
    

此方法与上一个方法相比,又减少了许多对不必要的数的遍历,效率更高

在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值