[Leetcode 50] 23 Merge K Sorted Lists

Problem:

Merge k sorted linked lists and return it as one sorted list. Analyze and describe its complexity.

 

Analysis:

Since each list is sorted, the second element won't be merged into the final list until the first element is merged. So we can scan the head of each list and find the minimum element to merge into the final result. Note how to process those empty list and when to exit the scan phase.

 

Code:

 1 /**
 2  * Definition for singly-linked list.
 3  * struct ListNode {
 4  *     int val;
 5  *     ListNode *next;
 6  *     ListNode(int x) : val(x), next(NULL) {}
 7  * };
 8  */
 9 class Solution {
10 public:
11     ListNode *mergeKLists(vector<ListNode *> &lists) {
12         // Start typing your C/C++ solution below
13         // DO NOT write int main() function
14         if (lists.size() == 0) return NULL;
15         
16         ListNode *head=NULL, *cur=NULL;
17         int  minIdx;
18         while (true) {
19             minIdx = -1;
20             for (int i=0; i<lists.size(); i++) {
21                 if (lists[i] != NULL) {
22                     if (minIdx == -1) 
23                         minIdx = i;
24                     else if (lists[i]->val < lists[minIdx]->val) {
25                         minIdx = i;
26                     }
27                 }
28             }
29             
30             if (minIdx == -1) break; //all list are NULL;
31             
32             if (head == NULL) {
33                 head = lists[minIdx];
34                 cur = lists[minIdx];
35             } else {
36                 cur->next = lists[minIdx];
37                 cur = cur->next;
38             }
39             
40             lists[minIdx] = lists[minIdx]->next;
41         }
42         
43         return head;
44     }
45 };
View Code

 

posted on 2013-05-26 02:09  freeneng  阅读(116)  评论(0编辑  收藏  举报

导航