自定义
# 1. 两数之和 - 力扣(LeetCode) (opens new window)
class Solution {
public int[] twoSum(int[] nums, int target) {
Map<Integer,Integer> hashtable = new HashMap<>();
for(int i = 0; i < nums.length; i++) {
if (hashtable.containsKey(target - nums[i])) {
return new int[]{hashtable.get(target - nums[i]), i};
} else {
hashtable.put(nums[i],i);
}
}
return new int[0];
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
2
3
4
5
6
7
8
9
10
11
12
13
# 146. LRU 缓存 - 力扣(LeetCode) (opens new window)
class LRUCache {
int cap;
LinkedHashMap<Integer, Integer> cache = new LinkedHashMap<>();
public LRUCache(int capacity) {
this.cap = capacity;
}
public int get(int key) {
if (!cache.containsKey(key)) return -1;
// 将 key 变为最近使用
recent(key);
return cache.get(key);
}
public void put(int key, int value) {
if (cache.containsKey(key)) {
// 修改 key 的值
cache.put(key, value);
// 将 key 变为最近使用
recent(key);
return;
}
if (cache.size() >= this.cap) {
// 链表头部就是最久未使用的 key
int oldestKey = cache.keySet().iterator().next();
cache.remove(oldestKey);
}
// 将新的 key 添加链表尾部
cache.put(key, value);
}
public void recent(int key) {
int value = cache.get(key);
// 删除 key,重新插入到队尾
cache.remove(key);
cache.put(key, value);
}
}
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
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
编辑 (opens new window)
上次更新: 2025/06/13, 00:51:28