Leetcode 23. Merge k Sorted Lists

来源:互联网 发布:co.nz 域名查询 编辑:程序博客网 时间:2024/06/05 17:53

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

题目大意:对于k个有序的链表,将其合并为一个有序的链表

通过归并的方法进行排序:

/** * 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.size() <= 0) return NULL;        //归并排序,        int allList = lists.size() - 1;                //先归并前配对个        for(int i = 0; i < allList; ++i)        {              ListNode* tyu = merge(lists[2*i],lists[2*i+1]);                                          lists.push_back(tyu);        }        vector<ListNode*>::iterator ite = lists.end();       return *--ite;    }        //对两个链表进行归并     ListNode* merge(ListNode* list1, ListNode* list2)     {       if(list1 == NULL && list2 == NULL) return NULL;              if(list1 == NULL)       {           return list2;       }              if(list2 == NULL)       {           return list1;       }               ListNode* pHead = NULL;       if(list1->val <= list2->val)       {           pHead = list1;           pHead->next = merge(list1->next, list2);       }       else       {           pHead = list2;           pHead->next = merge(list1,list2->next);       }              return pHead;     }};
下边通过最小堆的求解方法看的别人写的:

/** * Definition for singly-linked list. * struct ListNode { *     int val; *     ListNode *next; *     ListNode(int x) : val(x), next(NULL) {} * }; */struct cmp{    bool operator()(pair<ListNode*, int> a, pair<ListNode*, int> b) {        return a.first -> val > b.first -> val;    }};class Solution {public:    ListNode* mergeKLists(vector<ListNode*>& lists) {        // 构建小根堆,由于在计算中对于一个节点,需要知道其原本所属的链表编号,所以要用pair来记录        priority_queue<int, vector<pair<ListNode*, int> >, cmp> heap;        for (int i = 0; i < lists.size(); i++) {            if (lists[i] != NULL) {                heap.push(make_pair(lists[i], i));                lists[i] = lists[i] -> next;            }        }        // 构建答案链表        ListNode *head = new ListNode(0);        ListNode *tail = head;        // 当堆不为空时说明还没有完成        while (heap.size() > 0) {            // 不断从小根堆中选取最小值加入到答案的最后            tail -> next = heap.top().first;            tail = tail -> next;            int index = heap.top().second;            heap.pop();            // 并取出其对应链表的下一个元素加入到堆中            if (lists[index] != NULL) {                heap.push(make_pair(lists[index], index));                lists[index] = lists[index] -> next;            }        }        // 返回答案        return head -> next;    }};



0 0