624 字
3 分钟
【算法笔记】(九)堆结构常见题目
题目整理
1、合并 K 个升序链表
题目描述
给定一个链表数组,每个链表都已经按升序排列。
请将所有链表合并到一个升序链表中,返回合并后的链表。
Java 代码
public ListNode mergeKLists(ListNode[] lists) { // 小根堆 PriorityQueue<ListNode> queue = new PriorityQueue<>(new Comparator<ListNode>() { @Override public int compare(ListNode o1, ListNode o2) { return o1.val - o2.val; } });
// 把所有链表的头节点加入小根堆 for (ListNode node : lists) { if (node != null) { queue.add(node); } }
if (queue.isEmpty()) { return null; }
ListNode top = queue.poll(); if (top.next != null) { queue.add(top.next); }
ListNode result = top; ListNode now = top;
while (!queue.isEmpty()) { top = queue.poll(); now.next = top; now = top;
if (top.next != null) { queue.add(top.next); } }
return result;}2、线段重合
题目描述
每一个线段都有 start 和 end 两个数据项,表示这条线段在 X 轴上从 start 位置开始到 end 位置结束。
给定一批线段,求所有重合区域中最多重合了几个线段,首尾相接的线段不算重合。
例如:
- 线段
[1,2]和[2,3]不重合 - 线段
[1,3]和[2,3]重合
链接:
https://www.nowcoder.com/practice/1ae8d0b6bb4e4bcdbf64ec491f63fc37
Java 代码
public class Main {
public static int MaxN = 100000; public static int[][] line = new int[MaxN][2]; public static int n;
public static int[] heap = new int[MaxN]; public static int size = 0;
public static void main(String[] args) throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); StreamTokenizer in = new StreamTokenizer(br); PrintWriter out = new PrintWriter(new BufferedOutputStream(System.out));
while (in.nextToken() != StreamTokenizer.TT_EOF) { n = (int) in.nval; for (int i = 0; i < n; i++) { in.nextToken(); line[i][0] = (int) in.nval; in.nextToken(); line[i][1] = (int) in.nval; } out.println(compute()); }
out.flush(); out.close(); br.close(); }
private static int compute() { // 首先将所有的线段按照左边界从小到大排好序 // 然后利用小根堆,将右边界大于当前线段左边界的线段放入小根堆中 // 此时小根堆有多少条记录,就是跟当前线段有重合的线段数目 size = 0; int ans = 0;
Arrays.sort(line, 0, n, new Comparator<int[]>() { @Override public int compare(int[] o1, int[] o2) { return o1[0] - o2[0]; } });
for (int i = 0; i < n; i++) { while (size > 0 && heap[0] <= line[i][0]) { pop(); } add(line[i][1]); ans = Math.max(ans, size); }
return ans; }
private static void add(int i) { heap[size] = i; int index = size++;
while (heap[index] < heap[(index - 1) / 2]) { swap(index, (index - 1) / 2); index = (index - 1) / 2; } }
private static void pop() { swap(0, --size); int now = 0, l = 1;
while (l < size) { int best = l + 1 < size && heap[l + 1] < heap[l] ? l + 1 : l; if (heap[best] > heap[now]) { return; } swap(best, now); now = best; l = now * 2 + 1; } }
public static void swap(int a, int b) { int temp = heap[b]; heap[b] = heap[a]; heap[a] = temp; }}部分信息可能已经过时









