设计哈希映射

class MyHashMap {
public class Entry {
public int key;
public int value;
public Entry(int k, int v) {
key = k;
value = v;
}
}

private Entry[] data;
private static final int SIZE = 13_333;     // 10000 / 0.75
private static final int DELETED = -1;

public MyHashMap() {
    data = new Entry[SIZE];
}

public void put(int key, int value) {
    data[hash(key)] = new Entry(key, value);
}

public int get(int key) {
    Entry entry = data[hash(key)];
    return entry == null ? -1 : entry.value;
}

public void remove(int key) {
    data[hash(key)] = new Entry(DELETED, DELETED);
}

private int hash(int key) {
    int i = key % SIZE;
    while (data[i] != null && data[i].key != key) {
        i = (i + 1) % SIZE;
    }
    return i;
}

}

在这里插入图片描述
function linkNode(key,val){
this.key=key;
this.val=val;
this.next=null;
}

var MyHashMap = function() {
const N=2011;
const hash=new Array(N);
for(let i=0;i<hash.length;i++){
hash[i]=new linkNode();
}
this.hash=hash;
};

/**

  • value will always be non-negative.
  • @param {number} key
  • @param {number} value
  • @return {void}
    */
    MyHashMap.prototype.put = function(key, value) {
    const N=2011;
    const index=key%N;
    let head=this.hash[index];
    let cur=head;
    while(cur && cur.next){
    if(cur.next.key===key){
    cur.next.val=value;
    return ;
    }
    cur=cur.next;
    }
    const node=new linkNode(key,value);
    cur.next=node;
    };

/**

  • Returns the value to which the specified key is mapped, or -1 if this map contains no mapping for the key
  • @param {number} key
  • @return {number}
    */
    MyHashMap.prototype.get = function(key) {
    const N=2011;
    const index=key%N;
    let head=this.hash[index];
    let cur=head;
    while(cur && cur.next){
    if(cur.next.key===key){
    return cur.next.val;
    }
    cur=cur.next;
    }
    return -1;

};

/**

  • Removes the mapping of the specified value key if this map contains a mapping for the key
  • @param {number} key
  • @return {void}
    */
    MyHashMap.prototype.remove = function(key) {
    const N=2011;
    const index =key%N;
    let head=this.hash[index];
    let cur=head;
    while(cur && cur.next){
    if(cur.next.key===key){
    cur.next=cur.next.next;
    }
    cur=cur.next;
    }
    };

/**

  • Your MyHashMap object will be instantiated and called as such:
  • var obj = new MyHashMap()
  • obj.put(key,value)
  • var param_2 = obj.get(key)
  • obj.remove(key)
    */
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值