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

LeetCode: Merge k Sorted Lists [022]

时间:2014-05-18 09:05:40      阅读:255      评论:0      收藏:0      [点我收藏+]

标签:leetcode   算法   面试   

【题目】

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* merge(vector<ListNode*>&lists, int start, int end){
        if(start==end)return lists[start];
        int mid=(start+end)/2;
        ListNode*p1=merge(lists, start, mid);
        ListNode*p2=merge(lists, mid+1, end);
        ListNode*head=NULL, *p=NULL;
        while(p1&&p2){
            if(p1->val<p2->val){
                if(p)p->next=p1;
                p=p1;
                p1=p1->next;
            }
            else{
                if(p)p->next=p2;
                p=p2;
                p2=p2->next;
            }
            
            if(head==NULL)head=p;
        }
        if(p1){
            if(p)p->next=p1;
            else{p=p1;head=p;}
        }
        if(p2){
            if(p)p->next=p2;
            else{p=p2;head=p;}
        }
        return head;
    }
    ListNode *mergeKLists(vector<ListNode *> &lists) {
		int size=lists.size();
		if(size==0) return NULL;
		if(size==1) return lists[0];
		return merge(lists, 0, size-1);
    }
};


LeetCode: Merge k Sorted Lists [022],布布扣,bubuko.com

LeetCode: Merge k Sorted Lists [022]

标签:leetcode   算法   面试   

原文地址:http://blog.csdn.net/harryhuang1990/article/details/26007585

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