633. Sum of Square Numbers
Description
Given a non-negative integer c
, decide whether there're two integers a
and b
such that a2 + b2 = c
.
Example 1:
Input: c = 5 Output: true Explanation: 1 * 1 + 2 * 2 = 5
Example 2:
Input: c = 3 Output: false
Constraints:
0 <= c <= 231 - 1
Solutions
Solution: Two Pointers
- Time complexity: O(Math.sqrt(c))
- Space complexity: O(1)
JavaScript
js
/**
* @param {number} c
* @return {boolean}
*/
const judgeSquareSum = function (c) {
let left = 0;
let right = Math.floor(Math.sqrt(c));
while (left <= right) {
const sum = left ** 2 + right ** 2;
if (sum === c) return true;
sum > c ? (right -= 1) : (left += 1);
}
return false;
};