LeetCode706 设计哈希映射 -- 超详细

1、题目:https://leetcode-cn.com/problems/design-hashmap/

2、功能:实现哈希表,也就是HashMap的底层实现

(1)我们查看HashMap的源码:

3、代码

package com.leetcode;

/**
 * HashMap 是由 数组 + 单链表 组成
 * @author zhou
 *
 */
public class 设计哈希映射_2 {
	
	class MyHashMap {
		class Node{
			private int key;
			private int val;
			private Node next;
			public Node(int key,int val){
				this.key = key;
				this.val = val;
			}
		}
		
		private static final int N = 100011;
		Node[] table = null;

	    /** Initialize your data structure here. */
	    public MyHashMap() {
	    	this.table = new Node[N]; //初始化,数组中节点为Null
	    }
	    
	    /** value will always be non-negative. */
	    public void put(int key, int value) {
	    	Node cur = new Node(key,value);
	    	int idx = key % N;
	    	if(table[idx] == null){ //此处数组元素为空,则直接将新节点放进去
	    		table[idx] = cur;
	    	}else{ //此处数组元素不为空,则遍历数组下标所对应的链表
	    		Node tmp = table[idx];
	    		Node last = null;
	    		while(tmp != null){
	    			//1.键重复,则覆盖更新
	    			if(tmp.key == key){
	    				tmp.val = value;
	    				break;
	    			}else{ //2.键不存在不重复,则遍历下一个;
	    				last = tmp;
	    				tmp = tmp.next;
	    			}
	    		}
	    		//则插入到链表末尾
	    		if(tmp == null){
	    			last.next = cur;
	    		}
	    	}
	    }
	    
	    /** Returns the value to which the specified key is mapped, or -1 if this map contains no mapping for the key */
	    public int get(int key) {
	    	int idx = key % N;
	    	if(table[idx] == null) return -1;
	    	
	    	Node tar = table[idx];
	    	while(tar != null){ //索引到数组中对应的下标位置
	    		if(tar.key == key){
	    			return tar.val;
	    		}
	    		tar = tar.next; //继续对数组中对应的下标位置 的链表进行索引链表
	    	}
			return -1;
	    }
	    
	    /** Removes the mapping of the specified value key if this map contains a mapping for the key */
	    public void remove(int key) {
	    	int idx = key % N;
	    	if (table[idx] == null) return;
	    	
	    	Node tar = table[idx];
	    	Node pre = null;
    		Node after = null;
	    	while(tar != null){ //索引到数组中对应的下标位置
	    		//继续对数组中对应的下标位置 的链表进行索引链表
	    		while(tar.key != key){
	    			pre = tar;
	    			tar = tar.next;
	    		}
	    		//退出循环时,此时的tar正是目标节点
	    		after = tar.next;
	    		pre.next = after;
	    	}
	    }
	}

}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值