算法:哈希表
Java 哈希表题型模板与例题
一、计数类(Counting)
模板:
Map<Integer, Integer> map = new HashMap<>();
for (int num : nums) {map.put(num, map.getOrDefault(num, 0) + 1);
}
for (Map.Entry<Integer, Integer> entry : map.entrySet()) {if (entry.getValue() > n / 2) return entry.getKey();
}
例题:
- LeetCode 169. Majority Element
二、查找/去重类(Lookup / Deduplication)
模板:
Set<Integer> set = new HashSet<>();
for (int num : nums) {if (!set.add(num)) {// 已存在,处理逻辑}
}
例题:
- LeetCode 1. Two Sum
- LeetCode 217. Contains Duplicate
三、映射类(Mapping)
模板:
Map<Character, Character> map = new HashMap<>();
for (int i = 0; i < s.length(); i++) {if (!map.containsKey(s.charAt(i))) {map.put(s.charAt(i), t.charAt(i));} else if (map.get(s.charAt(i)) != t.charAt(i)) {return false;}
}
例题:
- LeetCode 205. Isomorphic Strings
- LeetCode 242. Valid Anagram
四、前缀和/累计和类(Prefix / Cumulative Sum)
模板:
Map<Integer, Integer> prefixSum = new HashMap<>();
prefixSum.put(0, 1);
int sum = 0, count = 0;
for (int num : nums) {sum += num;if (prefixSum.containsKey(sum - k)) count += prefixSum.get(sum - k);prefixSum.put(sum, prefixSum.getOrDefault(sum, 0) + 1);
}
例题:
- LeetCode 560. Subarray Sum Equals K
五、滑动窗口 + 哈希表
模板:
Map<Character, Integer> window = new HashMap<>();
int left = 0, right = 0;
while (right < s.length()) {char c = s.charAt(right++);window.put(c, window.getOrDefault(c, 0) + 1);while (window满足条件) {// 更新答案char d = s.charAt(left++);window.put(d, window.get(d) - 1);if (window.get(d) == 0) window.remove(d);}
}
例题:
- LeetCode 3. Longest Substring Without Repeating Characters
- LeetCode 76. Minimum Window Substring