LeetCode 23. Merge k Sorted Lists

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: []

Constraints:

k == lists.length
0 <= k <= 10^4
0 <= lists[i].length <= 500
-10^4 <= lists[i][j] <= 10^4
lists[i] is sorted in ascending order.
The sum of lists[i].length won't exceed 10^4.

实现思路:

就是合并K个链表,有许多的方法,这里只选择了一个优先队列法,起始本题最简单的办法就是将所有数据导入一个数组排序,构建链表即可,但是依旧选择优先队列来做是因为,本题如果要加大难度,就需要将整个链表结点不变化指针地址地保存下来排序成一个链表,那么就必须使用优先队列等方法了。

AC代码:

class Solution {
	public:
		ListNode* mergeKLists(vector<ListNode*>& lists) {
			priority_queue<int,vector<int>, greater<int>> q;//这是基本数据类型的写法 greater表示小根堆
			for(int i=0; i<lists.size(); i++) {
				ListNode *root=lists[i];
				while(root) {
					q.push(root->val);
					root=root->next;
				}
			}
			int size=q.size();
			ListNode *root=nullptr,*p=nullptr;
			while(size--) {
				int now=q.top();
				q.pop();
				ListNode *temp=new ListNode;
				temp->val=now;
				if(!p) {//重新组装链表
					root=temp;
					p=root;
				} else {
					p->next=temp;
					p=temp;
				}
				p->next=nullptr;
			}
			return root;
		}
};
posted @ 2021-03-08 20:50  coderJ_ONE  阅读(38)  评论(0编辑  收藏  举报