码迷,mamicode.com
首页 > 其他好文 > 详细

Merge k Sorted Lists

时间:2016-11-13 22:05:12      阅读:200      评论:0      收藏:0      [点我收藏+]

标签:null   排序   next   com   and   amp   scribe   exit   size   

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

标签:null   排序   next   com   and   amp   scribe   exit   size   

原文地址:http://www.cnblogs.com/willwu/p/6059921.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!