Why isn't my solution fast enough? Constant time for all operations.


  • 1
    A

    import java.util.HashSet;

    public class PhoneDirectory {

    HashSet<Integer> left, taken;
    /** Initialize your data structure here
        @param maxNumbers - The maximum numbers that can be stored in the phone directory. */
    public PhoneDirectory(int maxNumbers) {
        left = new HashSet<Integer>();
        taken = new HashSet<Integer>();
        for(int i=0; i<maxNumbers; i++){
            left.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() {
        int result = -1;
        if(left.isEmpty())
            return result;
        for(int i:left){
            result = i;
            break;
        }
        left.remove(result);
        taken.add(result);
        return result;
    }
    
    /** Check if a number is available or not. */
    public boolean check(int number) {
        return left.contains(number);
    }
    
    /** Recycle or release a number. */
    public void release(int number) {
        taken.remove(number);
        left.add(number);
    }
    

    }


  • -2

    The following code is not O(1)

    for(int i:left){
      result = i;
      break;
    }
    

  • 0
    H

    @ILoveGoogle I think it is O(1)


Log in to reply
 

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