Advertisement
Guest User

Untitled

a guest
Nov 17th, 2019
115
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 2.10 KB | None | 0 0
  1. //Runtime: 26 ms, faster than 93.11% of Java online submissions for Design HashMap.
  2. //Memory Usage: 54.6 MB, less than 43.24% of Java online submissions for Design HashMap.
  3. class MyHashMap {
  4.     int SIZE = 512;
  5.     List<List<Pair>> store;
  6.  
  7.     public MyHashMap() {
  8.         store = new ArrayList<List<Pair>>(SIZE);
  9.         for(int i = 0; i < SIZE; i++){
  10.             store.add(new LinkedList<Pair>());
  11.         }
  12.     }
  13.    
  14.     public void put(int key, int value) {
  15.         List<Pair> bucket = store.get(hash(key));
  16.         for (int i = 0; i < bucket.size(); i++){
  17.             Pair currentPair = bucket.get(i);
  18.             if(currentPair.key == key){
  19.                 currentPair.value = value;
  20.                 return;
  21.             }
  22.         }
  23.         bucket.add(new Pair(key, value));        
  24.     }
  25.    
  26.     public int get(int key) {
  27.         List<Pair> bucket = store.get(hash(key));
  28.         for (int i = 0; i < bucket.size(); i++){
  29.             Pair currentPair = bucket.get(i);
  30.             if(currentPair.key == key){
  31.                 return currentPair.value;
  32.             }
  33.         }
  34.         return -1;
  35.     }
  36.    
  37.     public void remove(int key) {
  38.         List<Pair> bucket = store.get(hash(key));
  39.         for (int i = 0; i < bucket.size(); i++){
  40.             if(bucket.get(i).key == key){
  41.                 bucket.remove(i);
  42.             }
  43.         }
  44.     }
  45.    
  46.     int hash(int key){
  47.         return key % SIZE;
  48.     }
  49. }
  50. class Pair{
  51.     int key;
  52.     int value;
  53.    
  54.     public Pair(int key, int value){
  55.         this.key = key;
  56.         this.value = value;
  57.     }
  58. }
  59.  
  60. //Eto ne hash tablica :)
  61. //Runtime: 22 ms, faster than 95.40% of Java online submissions for Design HashMap.
  62. //Memory Usage: 56.1 MB, less than 37.84% of Java online submissions for Design HashMap.
  63. class MyHashMap {
  64.     int[] array;
  65.     public MyHashMap() {
  66.         array = new int[1000001];
  67.     }
  68.    
  69.     public void put(int key, int value) {
  70.         array[key] = value + 1;
  71.     }
  72.    
  73.     public int get(int key) {
  74.         return array[key] - 1;
  75.     }
  76.    
  77.     public void remove(int key) {
  78.         array[key] = 0;
  79.     }
  80. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement