标签:des style blog class c code
Merge k sorted 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; } };
http://blog.csdn.net/jet_yingjia/article/details/26394567
[LeetCode]Merge k Sorted Lists,布布扣,bubuko.com
[LeetCode]Merge k Sorted Lists
标签:des style blog class c code
原文地址:http://blog.csdn.net/jet_yingjia/article/details/26362817