23. 合并K个升序链表
思路:
将两个有序链表合并,推广到n个链表的合并,就是将n个链表两两合并,再合并,就是归并排序的思维,现将数组递归到单个元素终止,然后执行两两merge。
https://leetcode-cn.com/problems/merge-k-sorted-lists/solution/he-bing-kge-pai-xu-lian-biao-by-leetcode-solutio-2/
/** * Definition for singly-linked list. * public class ListNode { * int val; * ListNode next; * ListNode() {} * ListNode(int val) { this.val = val; } * ListNode(int val, ListNode next) { this.val = val; this.next = next; } * } */ class Solution { public ListNode mergeKLists(ListNode[] lists) { if (lists == null || lists.length == 0) { return null; } return merge(lists, 0, lists.length - 1); } public ListNode merge(ListNode[] lists, int l, int r) { if (l == r) { return lists[l]; } if (l > r) { return null; } int mid = (l + r) >> 1; return mergeTwoListNode(merge(lists, l, mid), merge(lists, mid + 1, r)); } // 合并两个链表 public ListNode mergeTwoListNode(ListNode listNode1, ListNode listNode2) { ListNode head = new ListNode(-1); ListNode result=head; while (listNode1 != null && listNode2 != null) { if(listNode1.val<listNode2.val){ result.next=listNode1; listNode1=listNode1.next; }else { result.next=listNode2; listNode2=listNode2.next; } result=result.next; } if(listNode1!=null){ result.next=listNode1; }else { result.next=listNode2; } return head.next; } }
。。