您的位置:首页 > 其它

#104 Merge k Sorted Lists

2016-08-26 11:43 204 查看
题目思路:

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

Have you met this question in a real interview? 

Yes

Example

Given lists:
[
2->4->null,
null,
-1->null
],

return 
-1->2->4->null
.

题目思路:

这题的要求不是很严,那没有memory的限制,我就用map先把所有的nodes写入map中(key为val,value为所有val为key的nodes),然后再从map中取出来组成linkedlist就可以了。

Mycode(AC = 59ms):

/**
* Definition of ListNode
* class ListNode {
* public:
* int val;
* ListNode *next;
* ListNode(int val) {
* this->val = val;
* this->next = NULL;
* }
* }
*/
class Solution {
public:
/**
* @param lists: a list of ListNode
* @return: The head of one sorted list.
*/
ListNode *mergeKLists(vector<ListNode *> &lists) {
// write your code here
map<int, vector<ListNode*>> nodes;

// push all the nodes into map
for (int i = 0; i < lists.size(); i++) {
ListNode *head = lists[i];
while (head) {
nodes[head->val].push_back(head);
head = head->next;
}
}

// the nodes' value in map is sorted, just
// need to link the nodes from map
ListNode *dummy = new ListNode(0), *tmp = dummy;
for (auto it = nodes.begin(); it != nodes.end(); it++) {
for (int i = 0; i < it->second.size(); i++) {
tmp->next = it->second[i];
tmp = tmp->next;
}
}

return dummy->next;
}
};

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  lintcode linked list