Question:
You are given an array of linked lists, each of which has been sorted in ascending order.
Please merge all linked lists into an ascending linked list, and return the merged linked list.
Solution:
This question is really simple
, take a look at the data range
First of all, the sum of lists[i].length does not exceed 10^4, which means that we can put all the elements in each list into the priority queue, and then take them out one by one, but this is nlogn, which is still slow
Take another look, -10^4 <= lists[i][j] <= 10^4, directly ddd[20000], then there is no need to sort, the value of ddd[i] is equal to the value of i in all lists The number of elements, in this way, traverse all the lists, assign values to the ddd array, and finally traverse the ddd array again, create a linked list to save the results, no more
code show as below:
class Solution {
public:
int ddd[20005];
ListNode* mergeKLists(vector<ListNode*>& lists) {
for(int i = 0; i < lists.size(); i++) {
ListNode* temp = lists[i];
while(temp != NULL) {
ddd[(temp -> val) + 10000]++;
temp = temp -> next;
}
}
ListNode* res = new ListNode();
ListNode* temp = res;
for(int i = 0; i <= 20000; i++) {
while(ddd[i] != 0) {
temp -> next = new ListNode(i - 10000);
temp = temp -> next;
ddd[i]--;
}
}
return res -> next;
}
};