# int32bit / leetcode

Fetching latest commit…
Cannot retrieve the latest commit at this time.
Type Name Latest commit message Commit time
..
Failed to load latest commit information.
TLE_solve.cpp
solve.cpp
solve2.cpp

## Merge k Sorted Lists

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

## Solution 1

```class Solution {
public:
/**
* [] [[]]
*/
ListNode *mergeKLists(vector<ListNode*> &lists) {
int i = getMin(lists);
if (i < 0)
return nullptr;
lists[i] = lists[i]->next;
while ((i = getMin(lists)) != -1) {
p->next = lists[i];
lists[i] = lists[i]->next;
p = p->next;
}
p->next = nullptr;
}
private:
int getMin(vector<ListNode *> &lists) {
ListNode *minNode = nullptr;
int pos = -1;
bool updated = false;
int i;
for (i = 0; i < lists.size(); ++i) {
if (cmp(minNode, lists[i]) > 0) {
minNode = lists[i];
pos = i;
updated = true;
}
}
if (updated)
return pos;
else
return -1;
}
int cmp(ListNode *p, ListNode *q)
{
if (p == nullptr && q == nullptr)
return 0;
if (p == nullptr)
return 1;
if (q == nullptr)
return -1;
return p->val - q->val;
}
};```

## Solution 2

```ListNode *mergeKLists(vector<ListNode *> &lists) {
auto it_begin = begin(lists);
auto it_end = end(lists);
auto isNull = [](ListNode *p){return p == nullptr;};
auto minHeapPred = [](ListNode *t1, ListNode *t2){return t1->val > t2->val;};
it_end = remove_if(it_begin, it_end, isNull);
if (it_begin == it_end)
return nullptr;
make_heap(it_begin, it_end, minHeapPred);
while (distance(it_begin, it_end) > 1) {
pop_heap(it_begin, it_end, minHeapPred);
--it_end;
*it_end = (*it_end)->next;
if (*it_end) {
++it_end;
push_heap(it_begin, it_end, minHeapPred);
}
p->next = *it_begin;
p = p->next;
}
}```

## Solution 3 迭代法

```ListNode *mergeKLists_withMerge2(vector<ListNode *> &lists)
{
if (lists.empty())
return nullptr;
while (lists.size() > 1) {
lists.push_back(mergeTwoList(lists[0], lists[1]));
lists.erase(lists.begin());
lists.erase(lists.begin());
}
return lists.front();
}```

## Solution 4 分治法

```ListNode *mergeKLists_withMerge(vector<ListNode *> &lists, int s, int t)
{
if (s == t)
return lists[s];
if (t - s == 1) {
return mergeTwoList(lists[s], lists[t]);
}
int mid = s + ((t - s) >> 1);
ListNode *left = mergeKLists_withMerge(lists, s, mid);
ListNode *right = mergeKLists_withMerge(lists, mid + 1, t);
return mergeTwoList(left, right);
}```

## 扩展

You can’t perform that action at this time.