一、题目内容

image.png

二、题解

解法1:

思路

链表拼接+链表排序
要求复杂度 nlogn,所以归并排序

代码

  1. public class Solution {
  2. public ListNode mergeKLists(ArrayList<ListNode> lists) {
  3. if(lists == null||lists.isEmpty()){
  4. return null;
  5. }
  6. return sortListNode(mergeList(lists));
  7. }
  8. private ListNode mergeList(ArrayList<ListNode> lists){
  9. ListNode head = lists.get(0);
  10. ListNode dummy = new ListNode(-1);
  11. dummy.next = head;
  12. for(int i = 1;i<lists.size();i++){
  13. ListNode node = lists.get(i);
  14. while(head.next!=null){
  15. head = head.next;
  16. }
  17. head.next = node;
  18. while(head.next!=null){
  19. head = head.next;
  20. }
  21. }
  22. return dummy.next;
  23. }
  24. private ListNode sortListNode(ListNode head){
  25. // write code here
  26. if (head == null || head.next == null) {
  27. return head;
  28. }
  29. ListNode fast = head.next;
  30. ListNode slow = head;
  31. while (fast != null && fast.next != null) {
  32. fast = fast.next.next;
  33. slow = slow.next;
  34. }
  35. ListNode next = slow.next;
  36. slow.next = null;
  37. ListNode left = sortListNode(head);
  38. ListNode right = sortListNode(next);
  39. ListNode h = new ListNode(0);
  40. ListNode res = h;
  41. while (left != null && right != null) {
  42. if (left.val < right.val) {
  43. h.next = left;
  44. left = left.next;
  45. } else {
  46. h.next = right;
  47. right = right.next;
  48. }
  49. h = h.next;
  50. }
  51. h.next = left != null ? left : right;
  52. return res.next;
  53. }
  54. }