0633. Sum of Square Numbers - kumaeki/LeetCode GitHub Wiki

0633. Sum of Square Numbers


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

Example 3:

Input: c = 4

Output: true

Example 4:

Input: c = 2

Output: true

Example 5:

Input: c = 1

Output: true

Constraints:

  • 0 <= c <= 231 - 1

解法1

遍历.

class Solution {
    public boolean judgeSquareSum(int c) {
        double limit = Math.sqrt(c);
        for(int i = 0; i <= limit; i++){
            double d = Math.sqrt(c - i * i);
            if(d % 1 == 0) return true;
        }
        return false;
    }
}

解法2

滑动窗口

class Solution {
    public boolean judgeSquareSum(int c) {
        int i =0 , j = (int)Math.sqrt(c);
        while(i<=j){
            int powsum = i * i + j * j;
            if(powsum < c)
                i++;
            else if (powsum > c)
                j--;
            else
                return true;
        }
        return false;
    }
}
⚠️ **GitHub.com Fallback** ⚠️