Skip to content

Commit a0dd408

Browse files
committed
Runtime 26 ms (Top 64.39%) | Memory 14.0 MB (Top 16.21%)
1 parent 491068d commit a0dd408

File tree

1 file changed

+24
-45
lines changed

1 file changed

+24
-45
lines changed
Original file line numberDiff line numberDiff line change
@@ -1,49 +1,28 @@
1-
// To compare the elements of node
2-
class Comparator{
3-
4-
public:
5-
bool operator()(ListNode* n1, ListNode* n2){
6-
return n2->val < n1->val;
7-
}
8-
};
9-
101
class Solution {
11-
public:
12-
2+
public:
3+
struct compare
4+
{
5+
bool operator()(ListNode* &a,ListNode* &b)
6+
{
7+
return a->val>b->val;
8+
}
9+
};
1310
ListNode* mergeKLists(vector<ListNode*>& lists) {
14-
15-
int k=lists.size();
16-
17-
if(k==0) return NULL;
18-
19-
list<ListNode*> ll;
20-
21-
priority_queue<ListNode*, vector<ListNode*>, Comparator> minheap;
22-
23-
// push first element of every subarray in the minheap
24-
for(int i=0; i<k; i++){
25-
if(lists[i]) minheap.push(lists[i]);
26-
}
27-
28-
// push remaining elements
29-
while(!minheap.empty()){
30-
// take out top element
31-
ListNode* n =minheap.top();
32-
minheap.pop();
33-
// push the next element of its same array if exists
34-
if(n && n->next) minheap.push(n->next);
35-
36-
// minimum elements of the remaining will always be at top
37-
if(!ll.empty()){
38-
ll.back()->next=n;
39-
ll.push_back(n);
40-
}
41-
else{
42-
ll.push_back(n);
43-
}
11+
priority_queue<ListNode*,vector<ListNode*>,compare>minh;
12+
for(int i=0;i<lists.size();i++)
13+
{
14+
if(lists[i]!=NULL) minh.push(lists[i]);
15+
}
16+
ListNode* head=new ListNode(0);
17+
ListNode* temp=head;
18+
while(minh.size()>0)
19+
{
20+
ListNode* p=minh.top();
21+
minh.pop();
22+
temp->next=new ListNode(p->val);
23+
temp=temp->next;
24+
if(p->next!=NULL) minh.push(p->next);
4425
}
45-
46-
return ll.front();
47-
26+
return head->next;
4827
}
49-
};
28+
};

0 commit comments

Comments
 (0)