Use hashes but cannot pass the last testcase. Anyone has any idea?


  • 0
    Z

    I try to use a hashset to solve this problem, but it always time exceed. I think my solution's time complexity is O(1). Can anyone give me some advice? Or tell me why this happened? orz

    public class PhoneDirectory {
    
        Set<Integer> set;
        int max;
        int min;
        /** 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<Integer>();
            for(int i = 0; i < maxNumbers; i++) set.add(i);
            max = maxNumbers - 1;
            min = 0;
        }
        
        /** 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 res = set.iterator().next();
            set.remove(res);
            return res;
        }
        
        /** Check if a number is available or not. */
        public boolean check(int number) {
            if(number >= min && number <= max)
                return set.contains(number);
            else return false;
        }
        
        /** Recycle or release a number. */
        public void release(int number) {
            if(number > max || number < min) return;
            set.add(number);
            return;
        }
    }
    

Log in to reply
 

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