Simple Java solution with one set, complexity of all operations O(1)


  • 0
    P

    The idea is to simply use a set to store all the available numbers.

    public class PhoneDirectory {
        Set<Integer> set;
        public PhoneDirectory(int maxNumbers) {
            set = new HashSet();
            
            for (int i = 0; i < maxNumbers; i++) {
                set.add(i);
            }
        }
        
        public int get() {
            Iterator<Integer> it = set.iterator();
            if (it.hasNext()) {
                int ret = it.next();
                it.remove();
                return ret;
            } else {
                return -1;
            }
        }
        
        public boolean check(int number) {
            return set.contains(number);
        }
        
        public void release(int number) {
            set.add(number);
        }
    }
    

Log in to reply
 

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