23. Merge k Sorted Lists

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

Merge k sorted linked list就是merge 2 sorted linked list的变形题。

 

看准确写法:

每次有序地合并lists前两个链表,合并完放到队尾,再把前面已经合并的两个链表去掉。如此循环。

最终lists只剩下一个链表,这个链表就是有序合并了所有有序链表的最终结果

/**
 * 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.empty()){
        return nullptr;
    }
    while(lists.size() > 1){   //每次有序地合并前两个list,合并完放到队尾,再把前面已经合并的两个list去掉。
        lists.push_back(mergeTwoLists(lists[0], lists[1]));
        lists.erase(lists.begin());
        lists.erase(lists.begin());
    }
    return lists.front();
}
ListNode *mergeTwoLists(ListNode *l1, ListNode *l2) {   //有序合并两个链表list  递归
    if(l1 == nullptr){
        return l2;
    }
    if(l2 == nullptr){
        return l1;
    }
    if(l1->val <= l2->val){
        l1->next = mergeTwoLists(l1->next, l2);
        return l1;
    }
    else{
        l2->next = mergeTwoLists(l1, l2->next);
        return l2;
    }
}
}; 

 

傻瓜式算法,肯定不通过。time limited。贴上来是因为自己因为语法问题也调了好久的代码,因为会把java语法和c++语法弄混,链表和vector的语法问题

/**
 * 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) {
        vector<int> list;
        for(int i = 0; i < lists.capacity(); i++){  //把全部链表的全部元素放到一个容器内,之后统一排序...
            for(ListNode* node = lists[i] ; node; node = node->next){
                list.push_back(node->val);
            }
        }
        std::sort(list.begin(), list.end());   //注意排序函数写法
        ListNode node(0); 
        ListNode *L = &node;
        for(int i = 0; i < list.capacity(); i++){  //把排序后的容器内元素生成链表
            ListNode n(list[i]);
            L->next = &node;
            L = L->next;
        }
        return L->next; 
    }
}; 
 

 

posted @ 2017-11-13 20:35  hozhangel  阅读(125)  评论(0编辑  收藏  举报