Java Solution using HashSet


  • -1
    S
    This post is deleted!

  • 0
    N

    got the same idea, and you can merge two for loops into one

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

  • 1

    Same idea but didn't use Hashset though.

    public class Solution {
        public boolean judgeSquareSum(int c) {
            long C = c;
            long a_sq = 0,b=0;
            for(long i=1;i*i<=C;++i){
                a_sq = i*i;
                b = (long)Math.sqrt(c - a_sq);
                if(b*b == C-a_sq) return true;
            }
            return C == 0L;
        }
    }
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.