Advertisement
ogv

Untitled

ogv
Nov 17th, 2019
118
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.87 KB | None | 0 0
  1. // Runtime: 57 ms, faster than 89.47% of Java online submissions for Design HashMap.
  2. // Memory Usage: 54.5 MB, less than 43.24% of Java online submissions for Design HashMap.
  3. class MyHashMap {
  4.     int p;
  5.     List<Entry>[] table;
  6.    
  7.     /** Initialize your data structure here. */
  8.     public MyHashMap() {
  9.         p = 37;
  10.         table = new List[p];
  11.     }
  12.    
  13.     /** value will always be non-negative. */
  14.     public void put(int key, int value) {
  15.         List<Entry> list = table[key % p];
  16.         if (list == null) {
  17.             list = new LinkedList<Entry>();
  18.             table[key % p] = list;
  19.         }
  20.        
  21.         for (Entry e: list)
  22.             if (e.key == key) {
  23.                 e.value = value;
  24.                 return;
  25.             }
  26.        
  27.         list.add(new Entry(key, value));
  28.     }
  29.    
  30.     /** Returns the value to which the specified key is mapped, or -1 if this map contains no mapping for the key */
  31.     public int get(int key) {
  32.         List<Entry> list = table[key % p];
  33.         if (list == null) return -1;
  34.        
  35.         for (Entry e: list)
  36.             if (e.key == key) return e.value;
  37.        
  38.         return -1;
  39.     }
  40.    
  41.     /** Removes the mapping of the specified value key if this map contains a mapping for the key */
  42.     public void remove(int key) {
  43.         List<Entry> list = table[key % p];
  44.         if (list == null) return;
  45.        
  46.         ListIterator<Entry> iterator = list.listIterator();
  47.         while (iterator.hasNext()) {
  48.             Entry entry = iterator.next();
  49.             if (entry.key == key) {
  50.                 iterator.remove();
  51.                 return;
  52.             }
  53.         }
  54.     }
  55.    
  56.     class Entry {
  57.         public int key;
  58.         public int value;
  59.        
  60.         public Entry(int key, int value) {
  61.             this.key = key;
  62.             this.value = value;
  63.         }
  64.     }
  65. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement