Leetcode 633. Sum of Square Numbers
Given a non-negative integer c, determine whether there are two integers a and b such that:
[ a^2 + b^2 = c ]
Return true if there are such integers a and b, otherwise return false.
c guaranteed to be a non-negative integer?c?Answer:
c is guaranteed to be a non-negative integer.c usually fits within the range of a typical 32-bit signed integer.true or false.The problem can be approached using the two-pointer technique. Here’s the plan:
a) starts at 0.b) starts at the integer square root of c (i.e., the largest b such that b^2 <= c).a and b pointers.c, return true.c, increment a to increase the sum.c, decrement b to decrease the sum.a surpasses b.a surpasses b, return false, because no such pair (a, b) was found.public class Solution {
public boolean judgeSquareSum(int c) {
int a = 0;
int b = (int) Math.sqrt(c);
while (a <= b) {
int sum = a * a + b * b;
if (sum == c) {
return true;
} else if (sum < c) {
a++;
} else {
b--;
}
}
return false;
}
}
a and b together will move from 0 to the square root of c, so the overall time complexity of this part is (O(\sqrt{c})).Therefore, the overall time complexity is (O(\sqrt{c})), since the time complexity to find the square root is minimal compared to the two-pointer traversal. The space complexity is (O(1)) as we are using a constant amount of space.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?