合并K个升序链表

题目描述:给你一个链表数组,每个链表都已经按升序排列。

请你将所有链表合并到一个升序链表中,返回合并后的链表。

示例说明请见LeetCode官网。

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/merge-k-sorted-lists/
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

解法一:链表遍历
  • 首先,如果lists为null或者为空,直接返回null;
  • 然后,循环遍历数组中的链表,记录每一次遍历过程中的最小值min和相应的数组索引minIndex,将min放到结果result中,同时将数组索引为minIndex的链表往后移一位,遍历中止的条件就是当数组中所有的链表都为空时循环结束。 遍历结束后,返回结果result。
  1. public class LeetCode_023 {
  2. public static ListNode mergeKLists(ListNode[] lists) {
  3. if (lists == null || lists.length == 0) {
  4. return null;
  5. }
  6. int count = 0;
  7. ListNode result = new ListNode(-1);
  8. ListNode next = result;
  9. do {
  10. count = 0;
  11. int min = Integer.MAX_VALUE, minIndex = -1;
  12. for (int i = 0; i < lists.length; i++) {
  13. if (lists[i] != null) {
  14. count++;
  15. if (min > lists[i].val) {
  16. min = lists[i].val;
  17. minIndex = i;
  18. }
  19. }
  20. }
  21. if (count > 0) {
  22. next.next = new ListNode(min);
  23. lists[minIndex] = lists[minIndex].next;
  24. next = next.next;
  25. }
  26. } while (count > 0);
  27. return result.next;
  28. }
  29. public static void main(String[] args) {
  30. ListNode l1 = new ListNode(1);
  31. l1.next = new ListNode(4);
  32. l1.next.next = new ListNode(5);
  33. ListNode l2 = new ListNode(1);
  34. l2.next = new ListNode(3);
  35. l2.next.next = new ListNode(4);
  36. ListNode l3 = new ListNode(2);
  37. l3.next = new ListNode(6);
  38. ListNode result = mergeKLists(new ListNode[]{l1, l2, l3});
  39. while (result != null) {
  40. System.out.print(result.val + " ");
  41. result = result.next;
  42. }
  43. }
  44. }

【每日寄语】 当所有事情看起来都像在跟你作对时,请记得飞机也是逆风起飞的,而不是顺风而起。