Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // Runtime: 19 ms, faster than 99.96% of Java online submissions for Design HashMap.
- // Memory Usage: 49.4 MB, less than 97.30% of Java online submissions for Design HashMap.
- class MyList {
- protected int key;
- protected int value;
- protected MyList next;
- public MyList(int key, int value) {
- this.key = key;
- this.value = value;
- }
- }
- class MyHashMap {
- final int CAPACITY = 10000;
- protected MyList[] storage;
- public MyHashMap() {
- this.storage = new MyList[CAPACITY];
- }
- public void put(int key, int value) {
- MyList node = this.storage[this.hash(key)];
- if (node == null) {
- this.storage[this.hash(key)] = new MyList(key, value);
- return;
- }
- while (node != null) {
- if (node.key == key) {
- node.value = value;
- return;
- }
- if (node.next == null) {
- node.next = new MyList(key, value);
- return;
- }
- node = node.next;
- }
- }
- protected int hash(int key) {
- return key % CAPACITY;
- }
- public int get(int key) {
- MyList node = this.storage[this.hash(key)];
- while (node != null) {
- if (node.key == key) {
- return node.value;
- }
- node = node.next;
- }
- return -1;
- }
- public void remove(int key) {
- MyList node = this.storage[this.hash(key)];
- if (node == null) {
- return;
- }
- if (node.key == key) {
- this.storage[this.hash(key)] = node.next;
- }
- while (node != null) {
- if (node.next != null && node.next.key == key) {
- node.next = node.next.next;
- return;
- }
- node = node.next;
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement