|
1 | 1 | class MyHashMap {
|
2 | 2 |
|
3 |
| - /** Initialize your data structure here. */ |
4 |
| - Integer[][] map; |
5 |
| - int NUM_OF_BUCKETS = 1000; |
6 |
| - int BUCKET_SIZE = 1000; |
7 |
| - public MyHashMap() { |
8 |
| - map = new Integer[NUM_OF_BUCKETS][BUCKET_SIZE]; |
9 |
| - } |
| 3 | + private static final int BUCKET_COUNT = 1001; |
10 | 4 |
|
11 |
| - /** value will always be non-negative. */ |
12 |
| - public void put(int key, int value) { |
13 |
| - Integer[] bucket = getBucket(key); |
14 |
| - int keyHash = getKeyHash(key); |
15 |
| - bucket[keyHash] = value; |
16 |
| - } |
| 5 | + private static final int BUCKET_SIZE = 1001; |
17 | 6 |
|
18 |
| - /** Returns the value to which the specified key is mapped, or -1 if this map contains no mapping for the key */ |
19 |
| - public int get(int key) { |
20 |
| - Integer[] bucket = getBucket(key); |
21 |
| - int keyHash = getKeyHash(key); |
22 |
| - return bucket[keyHash] == null ? -1 : bucket[keyHash]; |
23 |
| - } |
| 7 | + private final Integer[][] map; |
24 | 8 |
|
25 |
| - /** Removes the mapping of the specified value key if this map contains a mapping for the key */ |
26 |
| - public void remove(int key) { |
27 |
| - Integer[] bucket = getBucket(key); |
28 |
| - int keyHash = getKeyHash(key); |
29 |
| - bucket[keyHash] = null; |
30 |
| - } |
31 |
| - |
32 |
| - private Integer[] getBucket(int key) { |
33 |
| - int bucketIdx = key / BUCKET_SIZE; |
34 |
| - return map[bucketIdx]; |
35 |
| - } |
36 |
| - |
37 |
| - private Integer getKeyHash(int key) { |
38 |
| - return key % BUCKET_SIZE; |
39 |
| - } |
| 9 | + public MyHashMap() { |
| 10 | + this.map = new Integer[BUCKET_COUNT][BUCKET_SIZE]; |
| 11 | + } |
| 12 | + |
| 13 | + public void put(int key, int value) { |
| 14 | + Position position = getPosition(key); |
| 15 | + map[position.bucket()][position.index()] = value; |
| 16 | + } |
| 17 | + |
| 18 | + public int get(int key) { |
| 19 | + Position position = getPosition(key); |
| 20 | + Integer value = map[position.bucket()][position.index()]; |
| 21 | + return value == null ? -1 : value; |
| 22 | + } |
| 23 | + |
| 24 | + public void remove(int key) { |
| 25 | + Position position = getPosition(key); |
| 26 | + map[position.bucket()][position.index()] = null; |
| 27 | + } |
| 28 | + |
| 29 | + private static Position getPosition(int key) { |
| 30 | + int bucket = key / BUCKET_COUNT; |
| 31 | + int index = key % BUCKET_SIZE; |
| 32 | + return new Position(bucket, index); |
| 33 | + } |
| 34 | + |
| 35 | + private static record Position(int bucket, int index) { |
| 36 | + |
| 37 | + } |
40 | 38 | }
|
41 | 39 |
|
42 | 40 | /**
|
|
0 commit comments