题目:
给定一个非负整数 c
,你要判断是否存在两个整数 a
和 b
,使得 a2 + b2 = c。
示例1:
输入: 5 输出: True 解释: 1 * 1 + 2 * 2 = 5
示例2:
输入: 3 输出: False
解题思路:
第一种方法是构建A^2 + B^2 = C,然后通过迭代两边逼近。
第二种方法使用哈希表进行查找,需要构建哈希表。
代码实现:
迭代逼近版本:
class Solution { public boolean judgeSquareSum(int c) { int start = 0; int end = (int) Math.sqrt(c); while (start <= end) { int remain = c - start * start - end * end; if (remain > 0) start ++; else if (remain == 0) return true; else end --; } return false; } }
哈希表版本:(没有逼近法快)
class Solution { public boolean judgeSquareSum(int c) { int start = 0; int end = (int) Math.sqrt(c); Map<Integer, Integer> map = new HashMap<Integer, Integer>(); // 构建哈希表 for (int i = end; i >= start; i --) { int tmp = i * i; map.put(tmp, tmp); if (map.containsKey(c - tmp)) return true; } return false; } }