题目描述
题目分析
- 这道题跟两数之和异曲同工,关键在于如何取尾指针的数
- 因为平方数中,只有 02 是最小的,仍为0,假定头指针的数为0 ,那么尾指针最大的数即为
target的开方
,这个可以使用Math.sqrt()
来计算
- 确定了尾指针的值过后,就跟两数之和的解法是一样的了
解法分析
- 因为题目中没有提到 a2 不能和 b2 相等,所以这里的头指针和尾指针是可以重合的
- 仍然使用while循环,直到两个指针相遇
代码
class Solution {
public boolean judgeSquareSum(int target) {
if (target < 0) return false;
int head = 0;
int end = (int) Math.sqrt(target);
while (head <= end){
int sum = head*head+end*end;
if (sum == target){
return true;
} else if (sum > target){
end--;
} else {
head++;
}
}
return false;
}
}