[Java] 706. Design a hash map---use a fixed-length array to represent MyHashMap! ! !

Design a hash map (HashMap) without using any built-in hash table library.

Implement the MyHashMap class:

MyHashMap() initializes the object with an empty map
void put(int key, int value) Insert a key-value pair (key, value) into the HashMap. If the key already exists in the map, update its corresponding value value.
int get(int key) Returns the value mapped by the specific key; if the mapping does not contain the key mapping, it returns -1.
void remove(key) If there is a key mapping in the mapping, remove the key and its corresponding value.

Example:

输入:
[“MyHashMap”, “put”, “put”, “get”, “get”, “put”, “get”, “remove”, “get”]
[[], [1, 1], [2, 2], [1], [3], [2, 1], [2], [2], [2]]
输出:
[null, null, null, 1, -1, null, 1, null, -1]

Explanation:
MyHashMap myHashMap = new MyHashMap();
myHashMap.put(1, 1); // myHashMap is now [[1,1]]
myHashMap.put(2, 2); // myHashMap is now [[1,1 ], [2,2]]
myHashMap.get(1); // returns 1, myHashMap is now [[1,1], [2,2]]
myHashMap.get(3); // returns -1 (not Found), myHashMap is now [[1,1], [2,2]]
myHashMap.put(2, 1); // myHashMap is now [[1,1], [2,1]] (updated Value)
myHashMap.get(2); // returns 1, myHashMap is now [[1,1], [2,1]]
myHashMap.remove(2); // delete the data with key 2, myHashMap is now [[1,1]]
myHashMap.get(2); // returns -1 (not found), myHashMap is now [[1,1]]

prompt:

0 <= key, value <= 106
call put, get and remove methods up to 104 times

代码:
    private int[]a=null;
	public MyHashMap() {
    
    
        a=new int[1000001];
        Arrays.fill(a,-1);
    }
    public void put(int key, int value) {
    
    
       a[key]=value;
    }
    public int get(int key) {
    
    
		return a[key];

    }
    public void remove(int key) {
    
    
        a[key]=-1;
    }

Guess you like

Origin blog.csdn.net/qq_44461217/article/details/114776909