|
2 | 2 | * @Author: Chacha
|
3 | 3 | * @Date: 2019-01-06 22:50:09
|
4 | 4 | * @Last Modified by: Chacha
|
5 |
| - * @Last Modified time: 2019-01-06 23:13:13 |
| 5 | + * @Last Modified time: 2019-02-18 22:11:29 |
6 | 6 | */
|
7 | 7 |
|
8 | 8 | #include<iostream>
|
9 | 9 | #include<string>
|
| 10 | +#include<vector> |
10 | 11 | using namespace std;
|
11 | 12 |
|
12 | 13 | /**
|
@@ -59,6 +60,67 @@ class Solution {
|
59 | 60 | lastNode->next = (l1 != NULL) ? l1 : l2;
|
60 | 61 | return dummy->next;
|
61 | 62 | }
|
| 63 | + |
| 64 | + /** |
| 65 | + * Merge k sorted linked lists and return it as one sorted list. |
| 66 | + * |
| 67 | + * Source: |
| 68 | + * https://leetcode.com/problems/merge-k-sorted-lists/ |
| 69 | + * https://leetcode.com/problems/merge-k-sorted-lists/solution/ |
| 70 | + * https://www.kancloud.cn/kancloud/data-structure-and-algorithm-notes/73014# |
| 71 | + * |
| 72 | + * |
| 73 | + * Solution 1 |
| 74 | + * @param lists: a list of ListNode |
| 75 | + * @return: The head of one sorted list. |
| 76 | + */ |
| 77 | + ListNode* mergeKLists1(vector<ListNode *> &lists) { |
| 78 | + if (lists.empty()) return NULL; |
| 79 | + |
| 80 | + ListNode* dummy = new ListNode(INT_MAX); |
| 81 | + ListNode* lastNode = dummy; |
| 82 | + |
| 83 | + while(true) { |
| 84 | + int count = 0; |
| 85 | + int index = -1, tempVal = INT_MAX; |
| 86 | + |
| 87 | + for(int i = 0; i != lists.size(); ++i) { |
| 88 | + if (lists[i] == NULL) { |
| 89 | + ++count; |
| 90 | + |
| 91 | + if (count == lists.size()) { |
| 92 | + lastNode->next = NULL; |
| 93 | + return dummy->next; |
| 94 | + } |
| 95 | + continue; |
| 96 | + } |
| 97 | + |
| 98 | + // choose the min value in non-NULL ListNode |
| 99 | + if (lists[i] != NULL && lists[i]->val <= tempVal) { |
| 100 | + tempVal = lists[i]->val; |
| 101 | + index = i; |
| 102 | + } |
| 103 | + } |
| 104 | + |
| 105 | + lastNode->next = lists[index]; |
| 106 | + lastNode = lastNode->next; |
| 107 | + lists[index] = lists[index]->next; |
| 108 | + } |
| 109 | + } |
| 110 | + |
| 111 | + /** |
| 112 | + * Solution 2 |
| 113 | + */ |
| 114 | + ListNode* mergeKLists2(vector<ListNode *> &lists) { |
| 115 | + if (lists.empty()) return NULL; |
| 116 | + |
| 117 | + ListNode* head = lists[0]; |
| 118 | + for(int i = 1; i != lists.size(); ++i) { |
| 119 | + head = mergeTwoLists(head, lists[i]); |
| 120 | + } |
| 121 | + |
| 122 | + return head; |
| 123 | + } |
62 | 124 | };
|
63 | 125 |
|
64 | 126 | /* Function to print nodes in a given linked list */
|
|
0 commit comments