23. 合并K个排序链表
2018-08-21 14:59 摘花 阅读(201) 评论(0) 编辑 收藏 举报合并 k 个排序链表,返回合并后的排序链表。请分析和描述算法的复杂度。
示例:
输入: [ 1->4->5, 1->3->4, 2->6 ] 输出: 1->1->2->3->4->4->5->6
思路;找到K个链表中表头val最小的node返回,把这个node连在合并链表的最后面
Java代码
class Solution { public ListNode mergeKLists(ListNode[] lists) { ListNode head = null, current = null; while (checkNode(lists)) { int t = getMinNodeIndex(lists); if (head == null) { head = lists[t]; current = lists[t]; } else { current.next = lists[t]; current = current.next; } lists[t] = lists[t].next; } return head; } private int getMinNodeIndex(ListNode[] lists) { int min = -1; for (int i = 0; i < lists.length; i++) { ListNode listNode = lists[i]; if (listNode != null) { if (min == -1) { min = i; } else { min = lists[min].val > listNode.val ? i : min; } } } return min; } private boolean checkNode(ListNode[] lists) { for (ListNode listNode : lists) { if (null != listNode) return true; } return false; } }