Using one HashSet, but got TLE?

  • 0

    I previously used a hashset and queue and passed all tests. However, when I used only one hashset, i got time limit exceeding. I think the main reason is because the 'iterator()' costs additional time. Shouldn't the 'iterator().next()' cost O(1) time???????

    Why I got a TLE???? Help!

    public class PhoneDirectory {
        Set<Integer> set;
        //Deque<Integer> list;
        /** Initialize your data structure here
            @param maxNumbers - The maximum numbers that can be stored in the phone directory. */
        public PhoneDirectory(int maxNumbers) {
            set = new HashSet<>();
            //list = new LinkedList<>();
            for (int i = 0; i < maxNumbers; i++) {
        /** Provide a number which is not assigned to anyone.
            @return - Return an available number. Return -1 if none is available. */
        public int get() {
            if (set.isEmpty()) return -1;
            int next = set.iterator().next();
            //int next = list.pollFirst();
            return next;
        /** Check if a number is available or not. */
        public boolean check(int number) {
            return (set.contains(number));
        /** Recycle or release a number. */
        public void release(int number) {
            if (!set.contains(number)) {

Log in to reply

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