Why I'm I getting TLE?


  • 0
    J

    The code works, but if you change
    HashSet set = new HashSet();
    to
    HashSet< Integer> set = new HashSet< Integer>();
    you get time limit exceeded. Why?

    And I thought you have to have < Integer>, but it works without. How?

    public class Solution {
        public boolean containsDuplicate(int[] nums) {
            HashSet set = new HashSet();
    
            for(int i = 0; i < nums.length; i++) {
                if(!set.contains(nums[i]))
                    set.add(nums[i]);
                else
                    return true;
            }
                
            return false;
            
        }
    }

  • 0

    "if you change HashSet set = new HashSet(); to HashSet set = new HashSet();"

    ... then you haven't changed anything.

    "And I thought you have to have ,"

    ... what?


  • 0
    J

    I think the less than and greater signs got embedded in the HTML. So I put a space to show. Remove the space in between the less than sign and Integer


  • 0

    Ah, ok. Alternatively you can use backticks to mark as code like HashSet<Integer> which won't be escaped.

    I just submitted both versions a few times and managed to get both AC (in 15ms) and TLE with both versions. Don't know why testing is that unstable.

    You can btw make it simpler and faster like this:

        for(int i = 0; i < nums.length; i++)
            if(!set.add(nums[i]))
                return true;
    

    Or even like this:

        for(int num : nums)
            if(!set.add(num))
                return true;
    

    But even though they're faster (AC in 9ms), I also managed to still get TLE with these. Really unstable testing for this problem.


  • 0
    J

    Cool. I didn't know that !set.add(num) returns false if it was already present.

    And For reason I thought Collections doesn't work with primitive types but yet it works with int when an autobox type isn't declared.


Log in to reply
 

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