LeetCode 23. Merge k Sorted Lists
2016-04-14 11:45
330 查看
问题
https://leetcode.com/problems/merge-k-sorted-lists/解法
使用priority_queue 维护一个小顶堆。共有k个链表, 所有链表共有n个节点。
复杂度 建立堆 k(logk)
堆中插入一个元素(logk)
共插入n次
总复杂度O(nlogk)
/** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode(int x) : val(x), next(NULL) {} * }; */ class compare{ public: bool operator()(ListNode* l1, ListNode* l2) { return l1->val > l2->val; } }; class Solution { public: ListNode* mergeKLists(vector<ListNode*>& lists) { ListNode Head(0); ListNode * ptr = &Head; priority_queue<ListNode*, vector<ListNode*>, compare> pq; for (int i=0; i<lists.size(); ++i) { if (lists[i]) pq.push(lists[i]); } while(pq.size() > 1) { ListNode *l = pq.top(); pq.pop(); ptr->next = l; ptr= ptr->next; l = l->next; if (l) pq.push(l); } ptr->next = pq.empty()? 0:pq.top(); return Head.next; } };
实现细节
priority_queue 的比较函数有两种定义方式,定义一个compare 类, 另一种是写一个cmp函数,然后将函数传入。class Foo { }; class Compare { public: bool operator() (Foo, Foo) { return true; } }; int main() { std::priority_queue<Foo, std::vector<Foo>, Compare> pq; return 0; }
class Foo { }; bool Compare(Foo, Foo) { return true; } int main() { std::priority_queue<Foo, std::vector<Foo>, std::function<bool(Foo, Foo)>> pq(Compare); return 0; }
priority_queue 默认是建立大顶堆:
Priority queues are a type of container adaptors, specifically designed such that its first element is always the greatest of the elements it contains, according to some strict weak ordering criterion.
如果在compare 中传入 < 则是构建大顶堆
传入> 则是构建小顶堆。
相关文章推荐
- leetcode 179 Largest Number
- leetcode 24 Swap Nodes in Pairs
- leetcode 2 Add Two Numbers 方法1
- leetcode 2 Add Two Numbers 方法2
- leetcode----Longest Substring Without Repeating Characters
- [LeetCode]47 Permutations II
- [LeetCode]65 Valid Number
- [LeetCode]123 Best Time to Buy and Sell Stock III
- [LeetCode] String Reorder Distance Apart
- [LeetCode] Sliding Window Maximum
- [LeetCode] Find the k-th Smallest Element in the Union of Two Sorted Arrays
- [LeetCode] Determine If Two Rectangles Overlap
- [LeetCode] A Distance Maximizing Problem
- leetcode_linearList
- leetcode_linearList02
- 021-Merge Two Sorted Lists(合并两个排好序的单链表);leetcode
- LeetCode[Day 1] Two Sum 题解
- LeetCode[Day 2] Median of Two Sorted Arrays 题解
- LeetCode[Day 3] Longest Substring Without... 题解
- LeetCode [Day 4] Add Two Numbers 题解