文章目录
思路:链地址法
代码:
java
复制代码
public class MyHashMap {
static class Node {
int key;
int val;
Node next;
public Node(int key, int val) {
this.key = key;
this.val = val;
}
}
Node[] nodes = new Node[10009];
public void put(int key, int value) {
int index = getIndex(key);
Node cur = nodes[index];
Node tmp = cur;
if (cur != null) {
Node prev = null;
while (tmp != null) {
if (tmp.key == key) {
tmp.val = value;
return;
}
prev = tmp;
tmp = tmp.next;
}
tmp = prev;//找到末尾
}
Node node = new Node(key, value);
//头插法
if (tmp != null) {
tmp.next = node;
} else {
nodes[index] = node;
}
}
public void remove(int key) {
int index = getIndex(key);
Node cur = nodes[index];
if (cur != null) {
Node prev = null;
while (cur != null) {
if (cur.key == key) {
if (prev != null) {
prev.next = cur.next;
} else {
nodes[index] = cur.next;
}
return;
}
prev = cur;
cur = cur.next;
}
}
}
public int get(int key) {
int hash = getIndex(key);
Node cur = nodes[hash];
if (cur!=null){
while (cur!=null){
if (cur.key == key){
return cur.val;
}
cur = cur.next;
}
}
return -1;
}
public int getIndex(int key){
int hash = Integer.hashCode(key);
//数组长度只有 10009,对应的十进制的 10011100011001
//返回的哈希值是32位的,右移16位的操作是为了将32位的哈希码中高16位的信息与低16位的信息进行混合
//将高位的信息混合到低位中,增加了哈希值的随机性, 均匀分布
hash ^= (hash >>> 16);
return hash % nodes.length;
}
}
思路:静态数组
代码:
java
复制代码
class MyHashMap {
private int[]data = new int[1000001];
public MyHashMap() {
Arrays.fill(data,-1);
}
public void put(int key, int value) {
data[key] = value;
}
public int get(int key) {
return data[key];
}
public void remove(int key) {
data[key] = -1;
}
}
思路:开放地址法
代码:
java
复制代码
public class MyHashMap2 {
static class Node {
int key;
int val;
boolean isDeleted;
Node next;
public Node(int key, int val) {
this.key = key;
this.val = val;
}
}
Node[] nodes = new Node[10009];
int OFFSET = 1;
public void put(int key, int value) {
int index = getIndex(key);
Node cur = nodes[index];
if (cur != null) {
cur.val = value;
cur.isDeleted = false;
}
Node node = new Node(key, value);
nodes[index] = node;
}
public void remove(int key) {
Node node = nodes[getIndex(key)];
if (node!=null){
node.isDeleted = true;
}
}
public int get(int key) {
if (nodes[getIndex(key)]==null){
return -1;
}
return nodes[getIndex(key)].isDeleted ? -1 : nodes[getIndex(key)].val;
}
private int getIndex(int key) {
int hash = Integer.hashCode(key);
hash ^= (hash >>> 16);
int index = hash % nodes.length;
while (nodes[index] != null && nodes[index].key != key) {
hash += OFFSET;
//该位置存在并且不等于key,哈希值进行偏移
//重新计算index;
index = hash % nodes.length;
}
return index;
}
点击移步博客主页,欢迎光临~