23. Merge k Sorted Lists 合并k个排序链表
2021/9/1 6:07:47
本文主要是介绍23. Merge k Sorted Lists 合并k个排序链表,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!
You are given an array of k
linked-lists lists
, each linked-list is sorted in ascending order.
Merge all the linked-lists into one sorted linked-list and return it.
Example 1:
Input: lists = [[1,4,5],[1,3,4],[2,6]] Output: [1,1,2,3,4,4,5,6] Explanation: The linked-lists are: [ 1->4->5, 1->3->4, 2->6 ] merging them into one sorted list: 1->1->2->3->4->4->5->6
Example 2:
Input: lists = [] Output: []
Example 3:
Input: lists = [[]] Output: [] 就是用q啊
/** * Definition for ListNode. * public class ListNode { * int val; * ListNode next; * ListNode(int val) { * this.val = val; * this.next = null; * } * } */ public class Solution { /** * @param lists: a list of ListNode * @return: The head of one sorted list. */ //comparator private Comparator<ListNode> ListNodeComparator = new Comparator<ListNode>() { public int compare(ListNode left, ListNode right) { return left.val - right.val; } }; public ListNode mergeKLists(ListNode[] lists) { //new heap if (lists.length == 0 || lists == null) { return null; } Queue<ListNode> heap = new PriorityQueue<ListNode>(lists.length,ListNodeComparator); for (int i = 0; i < lists.length; i++) { if (lists[i] != null) { //先加每个的head,1 1 2,然后小的才有资格继续加 4 3 //加进来之后一起去和2比较,2更小,然后继续加 //把整个的list加进去 heap.add(lists[i]); } } //add to the lists ListNode dummy = new ListNode(0); ListNode tail = dummy; while(!heap.isEmpty()) { ListNode head = heap.poll(); System.out.println("head = " + head.val); tail.next = head; tail = head; if (head.next != null) { System.out.println("添加的head.next = " + head.next.val); System.out.println(" "); heap.add(head.next); } } return dummy.next; } }
这篇关于23. Merge k Sorted Lists 合并k个排序链表的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!
- 2024-06-26结对编程到底难不难?答案在这里
- 2024-06-19《2023版Java工程师》课程升级公告
- 2024-06-15matplotlib作图不显示3D图,怎么办?
- 2024-06-1503-Loki 日志监控
- 2024-06-1504-让LLM理解知识 -Prompt
- 2024-06-05做软件测试需要懂代码吗?
- 2024-06-0514-ShardingSphere的分布式主键实现
- 2024-06-03为什么以及如何要进行架构设计权衡?
- 2024-05-31全网首发第二弹!软考2024年5月《软件设计师》真题+解析+答案!(11-20题)
- 2024-05-31全网首发!软考2024年5月《软件设计师》真题+解析+答案!(21-30题)