題解 | #合并k個已排序的鏈表#
合并k個已排序的鏈表
http://fangfengwang8.cn/practice/65cfde9e5b9b4cf2b6bafa5f3ef33fa6
import java.util.*; /* * public class ListNode { * int val; * ListNode next = null; * public ListNode(int val) { * this.val = val; * } * } */ public class Solution { /** * 代碼中的類名、方法名、參數(shù)名已經(jīng)指定,請勿修改,直接返回方法規(guī)定的值即可 * * * @param lists ListNode類ArrayList * @return ListNode類 */ public ListNode mergeKLists (ArrayList<ListNode> lists) { // write code here Queue<ListNode> priorityQueue = new PriorityQueue<>((v1, v2) -> v1.val - v2.val);//創(chuàng)造小根堆 for (int i = 0; i < lists.size(); i++) { if (lists.get(i) != null) { priorityQueue.add(lists.get(i)); } } ListNode res = new ListNode(-1); ListNode head = res; while (!priorityQueue.isEmpty()) { ListNode tmp = priorityQueue.poll(); head.next = tmp; head = head.next; //將tmp鏈表的下一個節(jié)點(diǎn)加入小根堆 if (tmp.next != null) { priorityQueue.add(tmp.next); } } return res.next; } }
最小值問題,多去想象小根堆實(shí)現(xiàn),小根堆的維護(hù)確保了堆頂一定是最小元素