Help! Why I get TLE here? [Java]


  • 0
    C

    I know the XOR solution. But when I tried to use a HashSet, I got time-limit-exceeded. Please Help!

    public class Solution {
        public int singleNumber(int[] A) {
            HashSet<Integer> set = new HashSet<Integer>();
            for (int i: A){
                if (!set.add(i))
                    set.remove(i);
            }
            if (set.iterator().hasNext())
                return set.iterator().next();
            return 0;
        }
    }

  • 0
    H

    try:

       public int singleNumber(int[] A) {
        HashSet<Integer> set = new HashSet<Integer>();
        for (int i: A){
            if (!set.add(i))
                set.remove(i);
        }
        Iterator<Integer> it = set.iterator();
        int result = Integer.MIN_VALUE;
        if (it.hasNext()) result = it.next();
        return result;
    }
    

    Just initiate the iterator.


  • 0
    D

    without extra memory see clearly next time


Log in to reply
 

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