Given a non-negative integer c, your task is to decide whether there're two integers a and b such that a2 + b2 = c.
public class Solution {
public boolean judgeSquareSum(int c) {
if(c == 0) return true;
int left = 0 , right = (int)Math.sqrt(c); //需要18ms,如果是用自己的算法,是12ms
// int mid ,temp = 0;
// while(temp == 0){
// mid = (left + right) / 2;
// if(mid > c / mid) {
// right = mid - 1;
// } else{
// if((mid + 1) > c / (mid + 1))
// temp = mid;
// left = mid + 1;
// }
// }
// right= temp;
// left = 0 ;
while(left <= right){
int m = left * left + right * right;
if( m > c) right--;
else {
if(m == c) return true;
left++;
}
}
return false;
}
}
这种类型的题目肯定是逃不了一个值一个值的试验,所以不要从纯数学的角度考虑怎么解题,而是考虑如果降低时间复杂度。1、缩小遍历范围 2、利用二分查找算法