[LeetCode]Merge k Sorted Lists
2014-05-20 13:59
267 查看
Merge k sorted
linked lists and return it as one sorted list. Analyze and describe its complexity.
网上看到使用优先队列做的:
优先队列的介绍:
/article/9177854.html
linked lists and return it as one sorted list. Analyze and describe its complexity.
/** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode(int x) : val(x), next(NULL) {} * }; */ class Solution { public: ListNode *mergeKLists(vector<ListNode *> &lists) { if (lists.size() == 0) { return NULL; } if (lists.size() == 1) { return lists[0]; } int pos = 0; int count = 0; for (int i = 0; i < lists.size(); i++) { ListNode* p = lists[i]; while(p != NULL) { count++; p = p->next; } } if (count > 0) { ListNode* ans = new ListNode(0); ListNode* ansTemp= ans; while(count) { int min = INT_MAX; for (int i = 0; i < lists.size(); i++) { if (lists[i] != NULL) { if ( (*lists[i]).val < min) { min = (*lists[i]).val; pos = i; } } } ansTemp->val = (*lists[pos]).val; if (count > 1) { ansTemp->next = new ListNode(0); ansTemp = ansTemp->next; } lists[pos] = lists[pos]->next; count--; } return ans; } else { return lists[0]; } } };
网上看到使用优先队列做的:
/** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode(int x) : val(x), next(NULL) {} * }; */ class Solution { public: struct comp { //优先队列中默认是less(<),top为最大的元素 //此处为greater(>),top为最小元素 bool operator() (ListNode *a,ListNode *b) { return a->val > b->val; } }; ListNode *mergeKLists(vector<ListNode *> &lists) { ListNode *tmphead = new ListNode(0), *p = tmphead; std::priority_queue<ListNode*, std::vector<ListNode*>, comp> q; for(int i = 0; i < lists.size(); i ++) { if(lists[i] != NULL) { q.push(lists[i]); } } while(!q.empty()) { p->next = q.top(); p = p->next; q.pop(); if(p ->next != NULL) { q.push(p->next); } } return tmphead->next; } };
优先队列的介绍:
/article/9177854.html
相关文章推荐
- 22 leetcode - Merge Two Sorted Lists
- leetcode:21 Merge Two Sorted Lists-每日编程第十七题
- LeetCode小白菜笔记[7]:Merge Two Sorted Lists
- LeetCode | Merge Two Sorted Lists
- LeetCode (Merge Two Sorted Lists)
- [LeetCode]Merge k Sorted Lists
- leetcode Merge Two Sorted Lists
- LeetCode 023 Merge k Sorted Lists
- 023 Merge k Sorted Lists [Leetcode]
- Leetcode 21. Merge Two Sorted Lists
- [LeetCode]23.Merge k Sorted Lists
- Leetcode 21 Merge Two Sorted Lists
- LeetCode(Merge Two Sorted Lists ) 合并两个有序的链表
- leetcode23---Merge k Sorted Lists
- 【LeetCode-23】Merge k Sorted Lists
- [LeetCode] Merge Two Sorted Lists 合并两个有序链表
- leetcode Merge k Sorted Lists
- leetcode - Merge Two Sorted Lists
- #leetcode#Merge K Sorted Lists
- LeetCode 21 Merge Two Sorted Lists