Merge k Sorted Lists

Posted Will Wu的学习笔记

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Merge k Sorted Lists相关的知识,希望对你有一定的参考价值。

Merge k Sorted Lists

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.empty())
        return nullptr;
      return helper(lists, 0 , lists.size()-1);
    }
private:
    ListNode* merge(ListNode* left, ListNode* right){
        ListNode* head = new ListNode(0);
        ListNode* last = head;
        while(left && right){
            if(left->val < right->val){
                last->next = left;
                left = left->next;
            }
            else{
                last->next = right;
                right = right->next;
            }
            last = last->next;
        }
        last->next = (left==nullptr)?  right: left;
        return head->next;
    }
    ListNode* helper(vector<ListNode*>& lists, int start, int end){
        cout << start << " "<<end <<endl;
        if(start == end)
            return lists[start];
        else if (start+1 ==end){
            return merge(lists[start], lists[end]);
        }
        ListNode* left = helper(lists, start, start+(end-start)/2);
        ListNode* right = helper(lists, start + (end - start) / 2 + 1, end);
        return merge(left,right);
        
    }
};

 

以上是关于Merge k Sorted Lists的主要内容,如果未能解决你的问题,请参考以下文章

leetcode-Merge k Sorted Lists

LeetCode 23 Merge k Sorted Lists

23. Merge k Sorted Lists

LeetCode-------merge-k-sorted-lists

leetcode23. Merge k Sorted Lists

Leetcode 23.Merge Two Sorted Lists Merge K Sorted Lists