Leetcode 023 Merge k Sorted Lists(优先队列)

题目连接:Leetcode 023 Merge k Sorted Lists

解题思路:用一个优先队列维护k个值,这k个值来自于k个有序队列的头结点,优先队列按照值排序,并且记录每个值对应来自哪个链表,每次取出最小的值,并从它所属的链表中补充进一个数(为空则不补充,优先队列维护k-1个数)。

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
	public:
		ListNode* mergeKLists(vector& lists) {
			ListNode head = ListNode(0);
			ListNode* ans = &head;
			ListNode* move = ans;

			priority_queue> que;
			for (int i = 0; i < lists.size(); i++) {
				if (lists[i] != NULL)
					que.push(make_pair(-lists[i]->val, i));
			}

			while (!que.empty()) {
				int t = que.top().second; que.pop();
				move->next = lists[t];
				lists[t] = lists[t]->next;
				if (lists[t] != NULL)
					que.push(make_pair(-lists[t]->val, t));
				move = move->next;
			}

			return ans->next;
		}
};

你可能感兴趣的:(Leetcode)