|
| 1 | +# [633. Sum of Square Numbers](https://leetcode.com/problems/sum-of-square-numbers) |
| 2 | + |
| 3 | +--- |
| 4 | + |
| 5 | +title: "Judging Square Sums in JavaScript" |
| 6 | +summary: "A detailed approach to solving the problem of determining if a given number can be expressed as the sum of two squares in JavaScript." |
| 7 | +date: "2024年06月17日" |
| 8 | +modified_date: "2024年06月17日" |
| 9 | +tags: ["JavaScript", "Algorithm", "Two Pointers", "Math"] |
| 10 | +slug: "judging-square-sums-in-javascript" |
| 11 | + |
| 12 | +--- |
| 13 | + |
| 14 | + |
| 15 | + |
| 16 | + |
| 17 | +# Intuition |
| 18 | + |
| 19 | +When given a number \( c \), the goal is to determine if it can be expressed as the sum of two squares. The first thought is to leverage a two-pointer approach to systematically check potential pairs of squares that sum to \( c \). |
| 20 | + |
| 21 | +# Approach |
| 22 | + |
| 23 | +To solve this problem, we use a two-pointer technique. One pointer starts at 0 (`left`), and the other starts at the largest possible integer whose square is less than or equal to \( c \) (`right`). We then iterate and adjust these pointers based on the sum of their squares: |
| 24 | + |
| 25 | +1. Calculate the sum of squares of the two pointers. |
| 26 | +2. If the sum equals \( c \), return true. |
| 27 | +3. If the sum is less than \( c \), increment the `left` pointer. |
| 28 | +4. If the sum is greater than \( c \), decrement the `right` pointer. |
| 29 | +5. Continue this process until the `left` pointer exceeds the `right` pointer. |
| 30 | + |
| 31 | +This method ensures that we efficiently explore all possible pairs of squares without redundancy. |
| 32 | + |
| 33 | +# Complexity |
| 34 | + |
| 35 | +- Time complexity: |
| 36 | + The time complexity of this approach is \( O(\sqrt{c}) \) because in the worst case, both pointers will traverse from 0 to \( \sqrt{c} \). |
| 37 | + |
| 38 | +- Space complexity: |
| 39 | + The space complexity is \( O(1) \) since we are only using a fixed amount of extra space for the two pointers and the sum calculation. |
| 40 | + |
| 41 | +# Code |
| 42 | + |
| 43 | +```javascript |
| 44 | +/** |
| 45 | + * @param {number} c |
| 46 | + * @return {boolean} |
| 47 | + */ |
| 48 | +function judgeSquareSum(c) { |
| 49 | + let left = 0; |
| 50 | + let right = Math.floor(Math.sqrt(c)); |
| 51 | + |
| 52 | + while (left <= right) { |
| 53 | + let sumOfSquares = left * left + right * right; |
| 54 | + if (sumOfSquares === c) { |
| 55 | + return true; |
| 56 | + } else if (sumOfSquares < c) { |
| 57 | + left++; |
| 58 | + } else { |
| 59 | + right--; |
| 60 | + } |
| 61 | + } |
| 62 | + |
| 63 | + return false; |
| 64 | +} |
0 commit comments