問題:ide
Given a non-negative integer c
, your task is to decide whether there're two integers a
and b
such that a^2 + b^2 = c.spa
Example 1:指針
Input: 5 Output: True Explanation: 1 * 1 + 2 * 2 = 5
Example 2:code
Input: 3 Output: False
解決:ci
① 使用雙指針查找是否存在知足條件的值。耗時12msio
public class Solution {
public boolean judgeSquareSum(int c) {
if (c < 0) return false;
int left = 0;
int right = (int)Math.sqrt(c);
while (left <= right) {
int sum = left * left + right * right;
if (sum < c) {
left ++;
} else if (sum > c) {
right --;
} else {
return true;
}
}
return false;
}
}class
② 因爲a*a+b*b=c,因此只須要從0到sqrt(c)遍歷,求得c-i*i的剩餘值,並對其進行開方,判斷它是不是一個整數,如果,返回true;不然,返回false。遍歷
public class Solution { //25ms
public static boolean judgeSquareSum(int c) {
for (int i = 0;i <= Math.sqrt(c);i ++)
if (Math.floor(Math.sqrt(c - i * i)) == Math.sqrt(c - i * i)) return true;//Math.floor()向下取整
return false;
}
}static
③ 進化版while
public class Solution { //22ms
public boolean judgeSquareSum(int c) {
for(int i = 0;i <= Math.sqrt(c);i ++){
if((int)Math.sqrt(c - i * i) == Math.sqrt(c - i * i)) return true; } return false; } }