- 平方数之和 难度 [中等]
给定一个非负整数 c ,你要判断是否存在两个整数 a 和 b,使得 a2 + b2 = c 。
示例 1:
输入:c = 5
输出:true
解释:1 * 1 + 2 * 2 = 5
示例 2:
输入:c = 3
输出:false
示例 3:
输入:c = 4
输出:true
示例 4:
输入:c = 2
输出:true
示例 5:
输入:c = 1
输出:true
提示:
- 0 <= c <= 2^31 - 1
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/sum-of-square-numbers
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
解法一:枚举
在求 aa+bb=c 时 只需要枚举 a , b可以用c-a*a开方得出
public boolean judgeSquareSum(int c) {
int max = (int) Math.sqrt(c);
for(int a =0;a<=max;a++){
int b = (int) Math.sqrt(c-a*a);
if((a*a+b*b)==c) return true;
}
return false;
}
方法二:双指针
max为c开方取整
头指针a从0开始,尾指针b从max开始,如果 aa+bb > c 则 b - - ,aa+bb < c 则 a++
public boolean judgeSquareSum(int c) {
int b = (int) Math.sqrt(c);
int a =0;
while(a<=b){
int sum = a*a+b*b;
if(sum==c){
return true;
}else if(sum>c){
b--;
}else{
a++;
}
}
return false;
}
此文章创于本人学习时的记录,如有错误或更优解还请指出