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; } }
此方法与上一个方法相比,又减少了许多对不必要的数的遍历,效率更高