哈希表

基础操作

put(K key, V value):将指定的键值对插入到 HashMap 中,若键已存在,则更新值。
get(Object key):根据键获取值,如果不存在该键,返回 null。
remove(Object key):根据键删除键值对。
containsKey(Object key):检查是否包含指定的键。
containsValue(Object value):检查是否包含指定的值。
size():返回 HashMap 中键值对的数量。
isEmpty():检查 HashMap 是否为空。
keySet():返回所有键的集合。
values():返回所有值的集合。
entrySet():返回 HashMap 中所有键值对的 Set 集合。
clear():清空所有元素。

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
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
import java.util.HashMap;
import java.util.Map;

public class HashMapExample {
public static void main(String[] args) {
// 创建 HashMap 实例
HashMap<String, Integer> map = new HashMap<>();

// 1. put() - 添加或更新元素
map.put("apple", 1); // key = "apple", value = 1
map.put("banana", 2); // key = "banana", value = 2
map.put("orange", 3); // key = "orange", value = 3

// 2. get() - 获取元素
System.out.println("Value for key 'apple': " + map.get("apple")); // 输出 1

// 3. containsKey() - 检查是否包含某个键
System.out.println("Contains key 'banana': " + map.containsKey("banana")); // 输出 true

// 4. containsValue() - 检查是否包含某个值
System.out.println("Contains value 2: " + map.containsValue(2)); // 输出 true

// 5. remove() - 删除某个键值对
map.remove("banana");
System.out.println("After removing 'banana': " + map);

// 6. size() - 获取大小
System.out.println("Size of map: " + map.size()); // 输出 2

// 7. isEmpty() - 检查是否为空
System.out.println("Is map empty? " + map.isEmpty()); // 输出 false

// 8. keySet() - 获取所有的键
System.out.println("All keys: " + map.keySet()); // 输出 [apple, orange]

// 9. values() - 获取所有的值
System.out.println("All values: " + map.values()); // 输出 [1, 3]

// 10. entrySet() - 获取所有的键值对
for (Map.Entry<String, Integer> entry : map.entrySet()) {
System.out.println(entry.getKey() + ": " + entry.getValue());
}

// 11. clear() - 清空所有元素
map.clear();
System.out.println("After clearing map: " + map); // 输出 {}
}
}

1. 两数之和

1
2
3
4
5
6
7
8
9
10
11
12
13
class Solution {
public int[] twoSum(int[] nums, int target) {
HashMap<Integer, Integer> mp = new HashMap<>();
for (int i = 0; i < nums.length; i++){
int temp = target - nums[i];
if (mp.containsKey(temp)){
return new int[]{mp.get(temp), i};
}
mp.put(nums[i], i);
}
return new int[0];
}
}

49. 字母异位词分组

128. 最长连续序列

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
class Solution {
public int longestConsecutive(int[] nums) {
Set<Integer> num_set = new HashSet<Integer>();
for (int num : nums){
num_set.add(num);
}

int ans = 0;
for (int num : num_set){
if (!num_set.contains(num - 1)){
int cur = num;
int temp = 1;

while (num_set.contains(cur + 1)){
cur++;
temp++;
}
ans = Math.max(ans, temp);
}
}
return ans;
}
}

作者

sonder

发布于

2025-01-13

更新于

2025-02-10

许可协议