LeetCode--Merge k Sorted Lists

来源:互联网 发布:牛股宝手机炒股软件 编辑:程序博客网 时间:2024/04/29 04:29

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

思路:分而治之。
这道题很容易联想到之前做过的Merge Two Sorted Lists,然后采用分而治之的策略,两两合并即可。
具体合并方法按照效率递增如下。

方法一:

class Solution {public:    ListNode *mergeKLists(vector<ListNode *> &lists) {        if (lists.size() == 0) return NULL;        ListNode *p = lists[0];        for (int i = 1; i < lists.size(); i++) {            p = mergeTwoLists(p, lists[i]);        }        return p;    }       ListNode* mergeTwoLists(ListNode* l1, ListNode* l2) {        ListNode dummy(0);        ListNode *tail=&dummy;        while(l1&&l2){            if(l1->val<l2->val){                tail->next=l1;                l1=l1->next;            }            else{                tail->next=l2;                l2=l2->next;            }            tail=tail->next;        }        tail->next=l1?l1:l2;        return dummy.next;    }};

方法二:

/** * 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){        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) {    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;    }}};

方法三:

/** * Definition for singly-linked list. * struct ListNode { *     int val; *     ListNode *next; *     ListNode(int x) : val(x), next(NULL) {} * }; */class Solution {public:    ListNode* partition(vector<ListNode*>&lists,int start,int end){        if(start==end){            return lists[start];        }        else if(start<end){            int mid=(start+end)/2;            ListNode* l1=partition(lists,start,mid);            ListNode* l2=partition(lists,mid+1,end);            return mergeTwoLists(l1,l2);        }        return NULL;     }    ListNode* mergeKLists(vector<ListNode*>& lists) {        return partition(lists,0,lists.size()-1);    }    ListNode* mergeTwoLists(ListNode* l1, ListNode* l2) {        ListNode dummy(0);        ListNode *tail=&dummy;        while(l1&&l2){            if(l1->val<l2->val){                tail->next=l1;                l1=l1->next;            }            else{                tail->next=l2;                l2=l2->next;            }            tail=tail->next;        }        tail->next=l1?l1:l2;        return dummy.next;    }};
原创粉丝点击