How to stop time limit exceeded?


  • 0
    A

    My solution:

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

    But it says time limit exceeded.
    Why? Wouldn't using a hash set be the most efficient? How are some people getting it to super low times in the graph? Thanks.


  • 0
    R
    public boolean containsDuplicate(int[] nums) {
        Set<Integer> set = new HashSet<>(3000);
        for(int i = 0 ; i < nums.length; i++){
            if(set.contains(nums[i]))
                return true;
            set.add(nums[i]);
        }
        return false;
    }

  • 0
    Z

    hashmap is better.

        HashMap<Integer, Integer> map = new HashMap<Integer, Integer>();
    	for (int i : nums) {
    		if (map.put(i, i) != null) return true;
    	}
        return false;

  • 0

    @anupkrish24 Try to submit at midnight ^_^ because I submit the first time and got TLE, after I tried another time I got AC


Log in to reply
 

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