Advertisement
K_S_

Untitled

Nov 17th, 2019
198
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.96 KB | None | 0 0
  1. public class MyHashMap {
  2.     public static void main(String[] args) {
  3.         MyHashMap m = new MyHashMap();
  4.  
  5.         m.put(1, 1);
  6.         m.put(2, 2);
  7.         m.put(13, 13);
  8.  
  9.         System.out.println(m.get(10));
  10.     }
  11.  
  12.     private static final int MAX_SIZE = 1000000;
  13.     int[] items;
  14.     int size = 10;
  15.  
  16.     public MyHashMap() {
  17.         items = new int[size];
  18.         initArray(items);
  19.     }
  20.  
  21.     private void initArray(int[] items) {
  22.         for (int i = 0; i < items.length; i++) {
  23.             items[i] = -1;
  24.         }
  25.     }
  26.  
  27.     public void put(int key, int value) {
  28.         resizeIfNeeded(key);
  29.         items[key] = value;
  30.     }
  31.  
  32.     private void resizeIfNeeded(int key) {
  33.         if (key > size) {
  34.             int newSize = calculateNewSize(key);
  35.             resize(newSize);
  36.         }
  37.     }
  38.  
  39.     private int calculateNewSize(int key) {
  40.         int tmpSize = size;
  41.         while (tmpSize < key && tmpSize < MAX_SIZE) {
  42.             tmpSize *= 2;
  43.             if(tmpSize > MAX_SIZE) {
  44.                 tmpSize = MAX_SIZE;
  45.             }
  46.         }
  47.         return tmpSize;
  48.     }
  49.  
  50.     private void resize(int newSize) {
  51.         int[] newItems = new int[newSize];
  52.         initArray(newItems);
  53.  
  54.         System.arraycopy(items, 0, newItems, 0, items.length);
  55.         items = newItems;
  56.         size = newSize;
  57.     }
  58.  
  59.     /**
  60.      * Returns the value to which the specified key is mapped, or -1 if this map contains no mapping for the key
  61.      */
  62.     public int get(int key) {
  63.         resizeIfNeeded(key);
  64.         return items[key];
  65.     }
  66.  
  67.     /**
  68.      * Removes the mapping of the specified value key if this map contains a mapping for the key
  69.      */
  70.     public void remove(int key) {
  71.         resizeIfNeeded(key);
  72.         items[key] = -1;
  73.     }
  74. }
  75. /**
  76.  * Your MyHashMap object will be instantiated and called as such:
  77.  * MyHashMap obj = new MyHashMap();
  78.  * obj.put(key,value);
  79.  * int param_2 = obj.get(key);
  80.  * obj.remove(key);
  81.  */
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement