码迷,mamicode.com
首页 > 其他好文 > 详细

379. Design Phone Directory

时间:2016-11-20 06:25:26      阅读:151      评论:0      收藏:0      [点我收藏+]

标签:initial   imu   long   tor   color   phone   directory   sig   i++   

379. Design Phone Directory

Design a Phone Directory which supports the following operations:

 

  1. get: Provide a number which is not assigned to anyone.
  2. check: Check if a number is available or not.
  3. release: Recycle or release a number.

 

Example:

// Init a phone directory containing a total of 3 numbers: 0, 1, and 2.
PhoneDirectory directory = new PhoneDirectory(3);

// It can return any available phone number. Here we assume it returns 0.
directory.get();

// Assume it returns 1.
directory.get();

// The number 2 is available, so return true.
directory.check(2);

// It returns 2, the only number that is left.
directory.get();

// The number 2 is no longer available, so return false.
directory.check(2);

// Release number 2 back to the pool.
directory.release(2);

// Number 2 is available again, return true.
directory.check(2);

class PhoneDirectory {
public:
    vector<int> nums;
    vector<bool> flag;
    int pos;
    /** Initialize your data structure here
        @param maxNumbers - The maximum numbers that can be stored in the phone directory. */
    PhoneDirectory(int maxNumbers) {
        pos = maxNumbers;
        nums.resize(maxNumbers);
        flag.resize(maxNumbers);
        for (int i = 0; i < maxNumbers; i++) {
            nums[i] = i;
            flag[i] = true;
        }
    }
    
    /** Provide a number which is not assigned to anyone.
        @return - Return an available number. Return -1 if none is available. */
    int get() {
        if (pos > 0) {
            int cur = nums[--pos];
            flag[cur] = false;
            return cur;
        }
        return -1;
    }
    
    /** Check if a number is available or not. */
    bool check(int number) {
        return flag[number];
    }
    
    /** Recycle or release a number. */
    void release(int number) {
        if (!flag[number]) {
            flag[number] = true;
            nums[pos++] = number;
        }
    }
};

/**
 * Your PhoneDirectory object will be instantiated and called as such:
 * PhoneDirectory obj = new PhoneDirectory(maxNumbers);
 * int param_1 = obj.get();
 * bool param_2 = obj.check(number);
 * obj.release(number);
 */

 

379. Design Phone Directory

标签:initial   imu   long   tor   color   phone   directory   sig   i++   

原文地址:http://www.cnblogs.com/fripside/p/6081817.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!