[leetcode]706. Design HashMap

[leetcode]706. Design HashMap


Analysis

年纪大了就会比较惜命~—— [ummmm~]

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.
设计一个hashmap~

Implement

class MyHashMap {
public:
    /** Initialize your data structure here. */
    MyHashMap() {
        for(int i=0; i<=1000000; i++)
            myMap[i] = -1;
    }

    /** value will always be non-negative. */
    void put(int key, int value) {
        myMap[key] = value;
    }

    /** Returns the value to which the specified key is mapped, or -1 if this map contains no mapping for the key */
    int get(int key) {
        return myMap[key];
    }

    /** Removes the mapping of the specified value key if this map contains a mapping for the key */
    void remove(int key) {
        myMap[key] = -1;
    }
private:
    int myMap[1000010];
};

/**
 * Your MyHashMap object will be instantiated and called as such:
 * MyHashMap obj = new MyHashMap();
 * obj.put(key,value);
 * int param_2 = obj.get(key);
 * obj.remove(key);
 */

下面是评论区一个大佬的方法,打败了99%,我的做法只打败了48%,心塞!

vector<int> hashMap;
    MyHashMap() {

    }

    /** value will always be non-negative. */
    void put(int key, int value) {
        if(key>=hashMap.size()) {
            for(int i=hashMap.size();i<=key;i++) hashMap.push_back(-1);
        }
        hashMap[key]=value;
    }

    /** Returns the value to which the specified key is mapped, or -1 if this map contains no mapping for the key */
    int get(int key) {
        if(key>=hashMap.size()) return -1;
        return hashMap[key];
    }

    /** Removes the mapping of the specified value key if this map contains a mapping for the key */
    void remove(int key) {
        if(key>=hashMap.size()) return;
        hashMap[key]=-1;
    }

猜你喜欢

转载自blog.csdn.net/weixin_32135877/article/details/81168617