[刷题防痴呆] 0633 - 平方数之和 (Sum of Squ

2021-12-15  本文已影响0人  西出玉门东望长安

题目地址

https://leetcode.com/problems/sum-of-square-numbers/

题目描述

633. 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

思路

关键点

代码

class Solution {
    public boolean judgeSquareSum(int c) {
        Set<Integer> set = new HashSet<>();
        for (int i = 0; i <= Math.sqrt(c); i++) {
            int num = i * i;
            set.add(num);            
            if (set.contains(c - num)) {
                return true;
            }
        }

        return false;
    }
}
上一篇 下一篇

猜你喜欢

热点阅读