Does HashSet is Slower than Array when we traversal same element?

  • 0

    I use blow code during the contest but I got TLE. All difference between AC code is second loop. Anyone can help me to solve this?

    My TLE code:

            Set<Integer> squares = new HashSet<>();
            for (int i = 0; i * i <= c; i++) {
                squares.add(i * i);
            for (int num : squares) {
                if (squares.contains(c - num)) return true;
            return false;

    AC Code:

            HashSet<Integer> hs = new HashSet<>();
            for (int i=0; i<=Math.sqrt(c); i++) {
                hs.add(i * i);
            for (int i=0; i<=Math.sqrt(c); i++){
                if (hs.contains(c - (i*i)))
                    return true;
            return false;

Log in to reply

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