Simple Java Solution using HashSet (42% of Java submissions)


  • 0

    Simple HashSet implementation to find the duplicate number in the array.
    Time Complexity - O(N)
    Space Complexity - O(N)

    public boolean containsDuplicate(int[] nums) {
            Set<Integer> set = new HashSet<Integer>();
            for(int num : nums){
                if(set.contains(num)) return true;
                else set.add(num);
            }
            return false;
    }
    

  • 0
    Z

    @inair I use " if(!set.add(num)) return true; ", why is it Time Limit Exceeded?


  • 0

    @zhouhangqi94
    would be better if you type the complete code or the loop which contains the line for better understanding of your problem.


  • 0
    M

    @inair
    boolean add(E e)
    Specified by:
    add in interface Collection<E>
    Parameters:
    e - element to be added to this set
    Returns:
    true if this set did not already contain the specified element

    if add returns false, that means the element we try to add is already present.


  • 0
    M

    @zhouhangqi94

    public boolean containsDuplicate(int[] nums) {
        if(nums == null) 
            return false;
        Set<Integer> set = new HashSet<Integer>();
        
        for(int num : nums) {
            if(!set.add(num))
                return true;
        }
        
        return false;
    }
    

    My solution is accepted.


  • 0

    @Molen Thank you for sharing, guess need to read more documentation. :D


  • 0
    Z

    @Molen I just cant see any differences between my answer and yours……I see the documentation before,it says that set.add(E e) calls map.put(e, PRESENT),so I thought its the reason why its Time Limit Exceeded,but now your code is accepted, I really don't understand why.


  • 0
    Z

    @Molen I tried the same code again,and now its accepted,really interesting


  • 0

    @zhouhangqi94 possibly a glitch, it happened with me too but on a different question.


  • 0
    T

    @Molen
    Time Limit Exceeded. I definitely dont know whats going on!


Log in to reply
 

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