题目
思路:双指针
- 双指针,一根
left
指向0
,一根right
指向sqrt(c)
- 如果
cur_sum == c
,返回true
- 如果
cur_sum < c
,说明应该变大,那么left += 1
如果
cur_sum > c
,说明应该缩小,那么right -= 1
代码:
class Solution {
public:
bool judgeSquareSum(int c) {
long long left = 0, right = sqrt(c);
while (left <= right) {
long long cur_sum = left * left + right * right;
if (cur_sum == c) {
return true;
} else if (cur_sum < c) {
left += 1;
} else if (cur_sum > c) {
right -= 1;
}
}
return false;
}
};