刷题模式
双指针、滑窗等。
30 分钟
刷题模式总结:常见题型与解题模板
这一课你将能做到
- 看到题目快速归类到「两数之和」「Top K」「区间合并」等模式
- 直接套用模板代码,减少思考成本
- 根据数据范围预判算法复杂度是否可行
为什么要学
刷题不是拼智商,是拼模式识别。95% 的中等题都是经典模式的变种。掌握 20 个核心模式,胜过做 200 道零散题目。
人话:就像学数学公式,遇到面积题就用 S=ab,遇到速度题就用 v=s/t。刷题也有公式。
先建立图像
题型 → 模式 → 模板 → 代码
两数之和 → 哈希表/双指针
Top K → 堆/快排选择
区间合并 → 排序+贪心
树遍历 → DFS/BFS
最短路 → Dijkstra/BFS
跟着做
步骤 1:哈希表模式
import java.util.*;
public class Main {
// 两数之和(无序数组)
public int[] twoSum(int[] nums, int target) {
Map<Integer, Integer> map = new HashMap<>();
for (int i = 0; i < nums.length; i++) {
int need = target - nums[i];
if (map.containsKey(need)) {
return new int[]{map.get(need), i};
}
map.put(nums[i], i);
}
return new int[]{-1, -1};
}
// 无重复最长子串
public int lengthOfLongestSubstring(String s) {
Map<Character, Integer> last = new HashMap<>();
int left = 0, max = 0;
for (int right = 0; right < s.length(); right++) {
char c = s.charAt(right);
if (last.containsKey(c) && last.get(c) >= left) {
left = last.get(c) + 1;
}
last.put(c, right);
max = Math.max(max, right - left + 1);
}
return max;
}
public static void main(String[] args) {
Main m = new Main();
int[] res = m.twoSum(new int[]{2,7,11,15}, 9);
System.out.println(res[0] + ", " + res[1]);
}
}
适用:查找、去重、统计频率。复杂度 O(n)。
步骤 2:Top K 模式
import java.util.*;
public class Main {
// 第 K 大元素
public int findKthLargest(int[] nums, int k) {
PriorityQueue<Integer> heap = new PriorityQueue<>(); // 小顶堆
for (int num : nums) {
heap.offer(num);
if (heap.size() > k) heap.poll();
}
return heap.peek();
}
// 前 K 高频
public List<Integer> topKFrequent(int[] nums, int k) {
Map<Integer, Integer> count = new HashMap<>();
for (int num : nums) count.put(num, count.getOrDefault(num, 0) + 1);
PriorityQueue<Map.Entry<Integer, Integer>> heap = new PriorityQueue<>(
Comparator.comparingInt(Map.Entry::getValue)
);
for (Map.Entry<Integer, Integer> e : count.entrySet()) {
heap.offer(e);
if (heap.size() > k) heap.poll();
}
List<Integer> res = new ArrayList<>();
while (!heap.isEmpty()) res.add(heap.poll().getKey());
return res;
}
public static void main(String[] args) {
Main m = new Main();
System.out.println(m.findKthLargest(new int[]{3,2,1,5,6,4}, 2)); // 5
}
}