leetcode 27: Merge k Sorted Lists
2013-01-11 04:38
253 查看
Merge k sorted linked lists and return it as one sorted list. Analyze and describe its complexity.
keypoints: 1 be familiar with use of pointer to pointer ** pre, no need for a dummy head node.
2. when the container need erase or insert, it's probably a sign of using list instead of vector.
3. when use erase or insert function in vector and list, the argument must be iterator not index. Whereas, the argument is index position in string class.
keypoints: 1 be familiar with use of pointer to pointer ** pre, no need for a dummy head node.
2. when the container need erase or insert, it's probably a sign of using list instead of vector.
3. when use erase or insert function in vector and list, the argument must be iterator not index. Whereas, the argument is index position in string class.
/** * 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) { // Start typing your C/C++ solution below // DO NOT write int main() function //if( lists.size() <= 1) return intervals; list<ListNode* > mylist; for( int i=0; i< lists.size(); i++){ if(lists[i] != NULL) { mylist.push_back( lists[i] ); } } ListNode * head = NULL; ListNode ** pre = &head; while( ! mylist.empty()) { list<ListNode* > :: iterator minIt = mylist.begin(); list<ListNode* > :: iterator it = mylist.begin(); while( ++it != mylist.end() ) { if( (*it)->val < (*minIt)->val ) { minIt = it; } } *pre = *minIt; if( (*minIt)->next == NULL ) { mylist.erase( minIt ); } else { (*minIt) = (*minIt)->next ; } pre = &( (*pre)->next); } return head; } };
相关文章推荐
- leetcode 27: Merge k Sorted Lists
- LeetCode-021 Merge Two Sorted Lists
- LeetCode – Refresh – Merge Two Sorted Lists
- leetcode 日经贴,Cpp code -Merge Two Sorted Lists
- LeetCode 21 Merge Two Sorted Lists(合并链表)
- leetcode 21. Merge Two Sorted Lists
- LeetCode Merge Two Sorted Lists
- ( Leetcode 23 ) Merge k Sorted Lists
- [LeetCode]Merge k Sorted Lists
- leetcode——21——Merge Two Sorted Lists
- Leetcode 21 Merge Two Sorted Lists
- [LeetCode] 053: Merge K Sorted Lists
- leetcode-Merge Two Sorted Lists
- LeetCode-23.Merge k Sorted Lists
- LeetCode: Merge Two Sorted Lists, Remove Duplicates/Element, strStr()
- LeetCode Merge Two Sorted Lists
- LeetCode 21 Merge Two Sorted Lists
- leetcode题解-23. Merge k Sorted Lists
- [LeetCode] Merge Two Sorted Lists
- [leetcode 23]Merge k Sorted Lists