Sorry, your browser cannot access this site
This page requires browser support (enable) JavaScript
Learn more >

设计hash集合、hash映射

题目1

lettcode-705题
难度:简单1633055736251

解题思路

既然说是一个HashSet,所以他就是一个不可重复的集合,就意味着在该集合中每个元素只能出现一次。

所以说我们就可以用boolean类型的数组来模拟出这样的一个集合

数组的索引就对应了set的key,数组所对应的布尔值就是set的value,当其为true1时就说明存在,否则就是不存在

具体实现方式如下

具体代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
class MyHashSet {

//创建一个boolean类型的数组
boolean[] map=null;
public MyHashSet() {
map=new boolean[1000001];
}

public void add(int key) {
map[key]=true;
}

public void remove(int key) {
map[key]=false;
}

public boolean contains(int key) {
if (map[key]==true){
return true;
}else {
return false;
}
}
}

题目2

lettcode-706题
难度:简单1633055736251

解题思路

从题目中我们可以看出来跟上一题差不多,无非是一个set一个map的差别

阅读题目要求我们可以知道对应的keyvalue 都是int 类型的,所以我们可以定义一个int类型的数组来存储数据

取值的时候如果取值为空就返回一个-1 ,所以我做了一个判断,判断是否有值

具体实现方式如下

具体代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
class MyHashMap {

// 创建一个int类型的数组
Integer[] map=null;
public MyHashMap() {
map=new Integer[1000001];
}

public void put(int key, int value) {
map[key]=value;
}

public int get(int key) {
if (map[key]!=null){
int value=map[key];
return value;
}else{
return -1;
}
}

public void remove(int key) {
map[key]=null;
}
}