Java AC solution with LinkedHashSet


  • 0
    F

    I'm not sure whether there is a Java LinkedHashSet solution. All three functions: get(), check((), release() have time complexity of O(1); only the constructor needs time of O(maxNumbers). The space complexity is also O(maxNumbers). Does anyone think it's a good one?

    public class PhoneDirectory {
        LinkedHashSet<Integer> available;
    
        public PhoneDirectory(int maxNumbers) {
            available = new LinkedHashSet<Integer>();
            for(int i = 0; i < maxNumbers; ++i) {
                available.add(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(available.isEmpty()) {
                return -1;
            }
            Iterator<Integer> it = available.iterator();
            int number = it.next();
            available.remove(number);
            return number;
        }
    
        /** Check if a number is available or not. */
        public boolean check(int number) {
            return available.contains(number);
        }
    
        /** Recycle or release a number. */
        public void release(int number) {
            available.add(number);
        }
    }

Log in to reply
 

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