Advertisement
Guest User

Untitled

a guest
Nov 17th, 2019
92
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.91 KB | None | 0 0
  1. // Runtime: 19 ms, faster than 99.96% of Java online submissions for Design HashMap.
  2. // Memory Usage: 49.4 MB, less than 97.30% of Java online submissions for Design HashMap.
  3.  
  4. class MyList {
  5. protected int key;
  6. protected int value;
  7. protected MyList next;
  8.  
  9. public MyList(int key, int value) {
  10. this.key = key;
  11. this.value = value;
  12. }
  13. }
  14.  
  15. class MyHashMap {
  16.  
  17. final int CAPACITY = 10000;
  18.  
  19. protected MyList[] storage;
  20.  
  21. public MyHashMap() {
  22. this.storage = new MyList[CAPACITY];
  23. }
  24.  
  25. public void put(int key, int value) {
  26. MyList node = this.storage[this.hash(key)];
  27. if (node == null) {
  28. this.storage[this.hash(key)] = new MyList(key, value);
  29. return;
  30. }
  31. while (node != null) {
  32. if (node.key == key) {
  33. node.value = value;
  34. return;
  35. }
  36. if (node.next == null) {
  37. node.next = new MyList(key, value);
  38. return;
  39. }
  40. node = node.next;
  41. }
  42. }
  43.  
  44. protected int hash(int key) {
  45. return key % CAPACITY;
  46. }
  47.  
  48. public int get(int key) {
  49. MyList node = this.storage[this.hash(key)];
  50. while (node != null) {
  51. if (node.key == key) {
  52. return node.value;
  53. }
  54. node = node.next;
  55. }
  56. return -1;
  57. }
  58.  
  59. public void remove(int key) {
  60. MyList node = this.storage[this.hash(key)];
  61. if (node == null) {
  62. return;
  63. }
  64. if (node.key == key) {
  65. this.storage[this.hash(key)] = node.next;
  66. }
  67. while (node != null) {
  68. if (node.next != null && node.next.key == key) {
  69. node.next = node.next.next;
  70. return;
  71. }
  72. node = node.next;
  73. }
  74. }
  75. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement