vimer linux kernel 爱好者

leetcode hashmap基本操作

2019-03-03

705 & 706

这两个leetcode 题目基本是很简单的一个类型,只要你把key自动填充到对应的数组位置即可, 但是,这样太直接了,效率上来说应该会有问题。所以,这并不是最优解。

#define NUM 1000010

typedef struct {
    int *arr;
} MyHashMap;

/** Initialize your data structure here. */

MyHashMap* myHashMapCreate() {
    MyHashMap *obj = malloc(sizeof(MyHashMap));

    if(!obj)
        return ;

    obj->arr = (int *)malloc(sizeof(int) * NUM);

    if(!obj->arr) // here may be a problem
        return ;
    memset(obj->arr, -1, NUM);
    return obj;

}

/** value will always be non-negative. */
void myHashMapPut(MyHashMap* obj, int key, int value) {
    obj->arr[key] = value;

}

/** Returns the value to which the specified key is mapped, or -1 if this map contains no mapping for the key */
int myHashMapGet(MyHashMap* obj, int key) {
    if(obj->arr[key] != -1)
        return obj->arr[key];

    return -1;
}

/** Removes the mapping of the specified value key if this map contains a mapping for the key */
void myHashMapRemove(MyHashMap* obj, int key) {
    if(obj->arr[key] == -1)
        return;

    obj->arr[key] = -1;
}

void myHashMapFree(MyHashMap* obj) {
    free(obj);
}

/**
 * Your MyHashMap struct will be instantiated and called as such:
 * MyHashMap* obj = myHashMapCreate();
 * myHashMapPut(obj, key, value);

 * int param_2 = myHashMapGet(obj, key);

 * myHashMapRemove(obj, key);

 * myHashMapFree(obj);
*/

上一篇 gcc的一些用法

Comments

Content