Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- //Runtime: 26 ms, faster than 93.11% of Java online submissions for Design HashMap.
- //Memory Usage: 54.6 MB, less than 43.24% of Java online submissions for Design HashMap.
- class MyHashMap {
- int SIZE = 512;
- List<List<Pair>> store;
- public MyHashMap() {
- store = new ArrayList<List<Pair>>(SIZE);
- for(int i = 0; i < SIZE; i++){
- store.add(new LinkedList<Pair>());
- }
- }
- public void put(int key, int value) {
- List<Pair> bucket = store.get(hash(key));
- for (int i = 0; i < bucket.size(); i++){
- Pair currentPair = bucket.get(i);
- if(currentPair.key == key){
- currentPair.value = value;
- return;
- }
- }
- bucket.add(new Pair(key, value));
- }
- public int get(int key) {
- List<Pair> bucket = store.get(hash(key));
- for (int i = 0; i < bucket.size(); i++){
- Pair currentPair = bucket.get(i);
- if(currentPair.key == key){
- return currentPair.value;
- }
- }
- return -1;
- }
- public void remove(int key) {
- List<Pair> bucket = store.get(hash(key));
- for (int i = 0; i < bucket.size(); i++){
- if(bucket.get(i).key == key){
- bucket.remove(i);
- }
- }
- }
- int hash(int key){
- return key % SIZE;
- }
- }
- class Pair{
- int key;
- int value;
- public Pair(int key, int value){
- this.key = key;
- this.value = value;
- }
- }
- //Eto ne hash tablica :)
- //Runtime: 22 ms, faster than 95.40% of Java online submissions for Design HashMap.
- //Memory Usage: 56.1 MB, less than 37.84% of Java online submissions for Design HashMap.
- class MyHashMap {
- int[] array;
- public MyHashMap() {
- array = new int[1000001];
- }
- public void put(int key, int value) {
- array[key] = value + 1;
- }
- public int get(int key) {
- return array[key] - 1;
- }
- public void remove(int key) {
- array[key] = 0;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement