给一个整数 c
, 你需要判断是否存在两个整数 a
和 b
使得 a^2 + b^2 = c
.
样例
给出 n = 5
返回 true
// 1 * 1 + 2 * 2 = 5
给出 n = -5
返回 false
解题思路1:
常规思路,两轮遍历,时间复杂度O(N^2)
public class Solution {
/**
* @param num: the given number
* @return: whether whether there're two integers
*/
public boolean checkSumOfSquareNumbers(int num) {
// write your code here
if(num < 0)
return false;
for(int i=0; i<=(int)Math.sqrt(num); i++){
for(int j=0; j<=(int)Math.sqrt(num); j++){
if(i*i + j*j == num)
return true;
}
}
return false;
}
}
解题思路2:
还有一种方法,只需遍历一次,原题可变形为j*j=num-i*i,i作为遍历对象,计算出的j如果开根号后是整数,则是ok的。
时间复杂度O(N)
public class Solution {
/**
* @param num: the given number
* @return: whether whether there're two integers
*/
public boolean checkSumOfSquareNumbers(int num) {
// write your code here
if(num < 0)
return false;
for(int i=0; i<=Math.sqrt(num); i++){
int temp = num - i*i;
if(Math.sqrt(temp) == (int)Math.sqrt(temp))
return true;
}
return false;
}
}