给定一个非负整数 c ,你要判断是否存在两个整数 a 和 b,使得 a2 + b2 = c。
示例1:
输入: 5
输出: True
解释: 1 * 1 + 2 * 2 = 5
示例2:
输入: 3
输出: False
解题思路:
利用双指针解法,首相将a指向0,将b指向sqrt© 判断a * a + b * b == c 如果成立 返回true
如果不成立
a * a + b * b > c 则将b–
a * a + b * b < c 则将a++
package com.mfq.leetcode.code633;
public class Solution {
public boolean judgeSquareSum(int c) {
int a = 0, b = (int) Math.sqrt((double) c);
while (a <= b) {
if (a * a + b * b == c) {
return true;
} else if (a * a + b * b < c) {
a++;
} else if (a * a + b * b > c) {
b--;
}
}
return false;
}
public static void main(String[] args) {
System.out.println(new Solution().judgeSquareSum(3));
}
}