-
Notifications
You must be signed in to change notification settings - Fork 0
/
Merge_k_sorted_list
51 lines (47 loc) · 1.46 KB
/
Merge_k_sorted_list
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
49
50
/*
Merge k Sorted Lists
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];
ListNode *head=new ListNode(INT_MIN);
head->next=lists[0];
for (int i=1; i<lists.size(); ++i)
{
ListNode *p1=head->next,*p2=lists[i],*p=head;
while(p1 && p2)
{
if (p1->val<=p2->val)
{
p->next=p1;
p=p1;
p1=p1->next;
}
else
{
p->next=p2;
p=p2;
p2=p2->next;
}
}
if (!p1) p->next=p2;
if (!p2) p->next=p1;
}
return head->next;
}
};
REMARK:
1. Medium difficulty. Thought for a while.Shouldn't have thought that long.
IDEA: Simple. Since we know how to merge 2 sorted list(a simpler problem that I did before in leetcode),we merge the 1st and 2nd list into a new list, then merge the new list with the 3rd list into a new one, then merge the new one with the 4th list and so forth.
2.Time complexity: O(n1+...+nk) where ni is the length of the lists[i].