题目

Design a HashMap without using any built-in hash table libraries.

To be specific, your design should include these functions:

  • put(key, value) : Insert a (key, value) pair into the HashMap. If the value already exists in the HashMap, update the value.
  • get(key): Returns the value to which the specified key is mapped, or -1 if this map contains no mapping for the key.
  • remove(key) : Remove the mapping for the value key if this map contains the mapping for the key.

Example:

  1. MyHashMap hashMap = new MyHashMap();
  2. hashMap.put(1, 1);
  3. hashMap.put(2, 2);
  4. hashMap.get(1); // returns 1
  5. hashMap.get(3); // returns -1 (not found)
  6. hashMap.put(2, 1); // update the existing value
  7. hashMap.get(2); // returns 1
  8. hashMap.remove(2); // remove the mapping for 2
  9. hashMap.get(2); // returns -1 (not found)

Note:

  • All keys and values will be in the range of [0, 1000000].
  • The number of operations will be in the range of [1, 10000].
  • Please do not use the built-in HashMap library.

题意

实现HashMap。

思路

直接开一个1000001大小的数组。


代码实现

Java

  1. class MyHashMap {
  2. int[] hash;
  3. /** Initialize your data structure here. */
  4. public MyHashMap() {
  5. hash = new int[1000001];
  6. Arrays.fill(hash, -1);
  7. }
  8. /** value will always be non-negative. */
  9. public void put(int key, int value) {
  10. hash[key] = value;
  11. }
  12. /** Returns the value to which the specified key is mapped, or -1 if this map contains no mapping for the key */
  13. public int get(int key) {
  14. return hash[key];
  15. }
  16. /** Removes the mapping of the specified value key if this map contains a mapping for the key */
  17. public void remove(int key) {
  18. hash[key] = -1;
  19. }
  20. }