leetcode706_设计哈希表


private int capacity = 16;
private int[] container;
private boolean[] table;

public MyHashMap() {
    this.container = new int[capacity];
    this.table = new boolean[capacity];
}

private void expand(int key) {
    int newCapacity = capacity;
    while(newCapacity <= key) newCapacity <<= 1;
    int[] newContainer = new int[newCapacity];
    boolean[] newTable = new boolean[newCapacity];
    for(int i = 0; i < capacity; i++) {
        newContainer[i] = container[i];
        newTable[i] = table[i];
    }
    container = newContainer;
    table = newTable;
    capacity = newCapacity;
}

public void put(int key, int value) {
    if(key > capacity) expand(key);
    container[key] = value;
    table[key] = true;
}

public int get(int key) {
    if(key > capacity) expand(key);
    if(table[key]) {
        return container[key];
    }
    else {
        return -1;
    }
}

public void remove(int key) {
    if(key > capacity) expand(key);
    table[key] = false;
}