LeetCode刷题笔记(链表):merge-k-sorted-lists



[toc]

题目描述

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

解题思路

之前做过一道题是对两个排序链表进行合并,这次是k个。所以,需要在原来的基础长做一些封装。

按照归并排序的思想,我们通过二分法得到中点进行递归,自下而上进行两两归并,直到只剩最后一个链表。

C++版代码实现

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
/**
* 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;
return mergeList(lists, 0, lists.size()-1);
}

ListNode *mergeList(vector<ListNode *> &lists, int low, int high){
if(high <= low)
return lists[low];
int mid = (low + high) / 2;
ListNode *left = mergeList(lists, low, mid);
ListNode *right = mergeList(lists, mid+1, high);
return merge(left, right);
}

ListNode *merge(ListNode *left, ListNode *right) {
if(left == NULL)
return right;
if(right == NULL)
return left;

ListNode *dummy = new ListNode(0);
ListNode *cur = dummy;
while(left != NULL && right != NULL){
if(left->val < right->val){
cur->next = left;
left = left->next;
}
else{
cur->next = right;
right = right->next;
}
cur = cur->next;
}
cur->next = left ? left : right;
return dummy->next;
}
};

系列教程持续发布中,欢迎订阅、关注、收藏、评论、点赞哦~~( ̄▽ ̄~)~

完的汪(∪。∪)。。。zzz

0%