LeetCode 22. Merge k Sorted Lists

用一个最小堆盛放所有有序链表的头结点即可。

复杂度O(nlogm) -- n为结点总数,m为vector.size()


代码:

class Solution 
{
public:
	struct cmp
	{
		bool operator () (const ListNode* a, const ListNode* b)
		{
			return a->val > b->val;
		}
	};
	ListNode *mergeKLists(vector<ListNode *> &lists) 
	{
		ListNode *head=NULL, *cur=NULL;
		priority_queue<ListNode*, vector<ListNode*>, cmp> ss;

		for (auto it = lists.begin(); it != lists.end(); ++ it)
		{
			if (*it != NULL)
			{
				ss.push(*it);
			}
		}
		while(ss.empty() == false)
		{
			auto top = ss.top();
			if (head == NULL)
			{
				head = cur = top;
			} else
			{
				cur->next = top;
				cur = cur->next;
			}
			ss.pop();
			if (top->next != NULL)
			{
				ss.push(top->next);
			}
		}

		return head;
	}
};


你可能感兴趣的:(LeetCode,C++,priority_queue)