Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- public class MyHashMap {
- public static void main(String[] args) {
- MyHashMap m = new MyHashMap();
- m.put(1, 1);
- m.put(2, 2);
- m.put(13, 13);
- System.out.println(m.get(10));
- }
- private static final int MAX_SIZE = 1000000;
- int[] items;
- int size = 10;
- public MyHashMap() {
- items = new int[size];
- initArray(items);
- }
- private void initArray(int[] items) {
- for (int i = 0; i < items.length; i++) {
- items[i] = -1;
- }
- }
- public void put(int key, int value) {
- resizeIfNeeded(key);
- items[key] = value;
- }
- private void resizeIfNeeded(int key) {
- if (key > size) {
- int newSize = calculateNewSize(key);
- resize(newSize);
- }
- }
- private int calculateNewSize(int key) {
- int tmpSize = size;
- while (tmpSize < key && tmpSize < MAX_SIZE) {
- tmpSize *= 2;
- if(tmpSize > MAX_SIZE) {
- tmpSize = MAX_SIZE;
- }
- }
- return tmpSize;
- }
- private void resize(int newSize) {
- int[] newItems = new int[newSize];
- initArray(newItems);
- System.arraycopy(items, 0, newItems, 0, items.length);
- items = newItems;
- size = newSize;
- }
- /**
- * Returns the value to which the specified key is mapped, or -1 if this map contains no mapping for the key
- */
- public int get(int key) {
- resizeIfNeeded(key);
- return items[key];
- }
- /**
- * Removes the mapping of the specified value key if this map contains a mapping for the key
- */
- public void remove(int key) {
- resizeIfNeeded(key);
- items[key] = -1;
- }
- }
- /**
- * Your MyHashMap object will be instantiated and called as such:
- * MyHashMap obj = new MyHashMap();
- * obj.put(key,value);
- * int param_2 = obj.get(key);
- * obj.remove(key);
- */
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement