题:https://leetcode.com/problems/sum-of-square-numbers/submissions/1
题目
Given a non-negative integer c, your task is to decide whether there’re two integers a and b such that a2 + b2 = c.
Example 1:
Input: 5
Output: True
Explanation: 1 * 1 + 2 * 2 = 5
Example 2:
Input: 3
Output: False
思路
题目大意
给定一个数 c,c求 是否存在a,b使得a2 + b2 = c
解题思路
参考 Two Sum。pleft 指针为 0,pright为可能的最大值。求其平方的和 与 c比较,并相应移动两指针。
code
class Solution {
public boolean judgeSquareSum(int c) {
int i = 0,j = (int)Math.sqrt(c);
while(i<=j){
int tsum = i*i + j*j;
if(tsum<c) i++;
else if(tsum>c) j--;
else return true;
}
return false;
}
}