//合并 k 个排序链表,返回合并后的排序链表。请分析和描述算法的复杂度。 // // 示例: // // 输入: //[ // 1->4->5, // 1->3->4, // 2->6 //] //输出: 1->1->2->3->4->4->5->6 // Related Topics 堆 链表 分治算法 package leetcode.editor.cn; //Java:合并K个排序链表 public class P23MergeKSortedLists { public static void main(String[] args) { Solution solution = new P23MergeKSortedLists().new Solution(); // TO TEST ListNode listNode1_1 = new ListNode(1); ListNode listNode1_2 = new ListNode(4); ListNode listNode1_3 = new ListNode(5); listNode1_1.next = listNode1_2; listNode1_2.next = listNode1_3; ListNode listNode2_1 = new ListNode(1); ListNode listNode2_2 = new ListNode(3); ListNode listNode2_3 = new ListNode(4); listNode2_1.next = listNode2_2; listNode2_2.next = listNode2_3; ListNode listNode3_1 = new ListNode(2); ListNode listNode3_2 = new ListNode(6); listNode3_1.next = listNode3_2; // System.out.println(solution.mergeKLists(new ListNode[]{listNode1_1, listNode2_1, listNode3_1})); } //leetcode submit region begin(Prohibit modification and deletion) /** * Definition for singly-linked list. * public class ListNode { * int val; * ListNode next; * ListNode(int x) { val = x; } * } */ class Solution { public ListNode mergeKLists(ListNode[] lists) { int length = lists.length; if (lists == null || length < 1) { return null; } else if (length == 1) { return lists[0]; } ListNode result = null; ListNode min; ListNode pointResult = null; int pointX; while (true) { min = null; pointX = 0; for (int x = 0; x < length; x++) { if (lists[x] != null) { if (min == null || (lists[x].val < min.val)) { pointX = x; min = lists[x]; } } } if (min == null) { break; } lists[pointX] = min.next; if (result == null) { result = new ListNode(min.val); pointResult = result; } else { pointResult.next = new ListNode(min.val); pointResult = pointResult.next; } } return result; } } //leetcode submit region end(Prohibit modification and deletion) }
Java:合并K个排序链表
最新推荐文章于 2024-08-18 23:05:29 发布