zoukankan      html  css  js  c++  java
  • 23. Merge k Sorted Lists

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

    Example:

    Input:
    [
      1->4->5,
      1->3->4,
      2->6
    ]
    Output: 1->1->2->3->4->4->5->6


    直接复用归并排序即可

    /**
     * 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) {
            ListNode *res=NULL;
            for(int i=0;i<lists.size();++i)
            {
                if(NULL==res)
                {
                    res=lists[i];
                    continue;
                }
                res=merge(res,lists[i]);
            }
            return res;
        }
        
        ListNode* merge(ListNode *l1,ListNode *l2) {
            if(NULL==l1)return l2;
            if(NULL==l2)return l1;
            if(l1->val<l2->val)
            {
                l1->next=merge(l1->next,l2);
                return l1;
            }
            
            l2->next=merge(l1,l2->next);
            return l2;
        }
    };
  • 相关阅读:
    从原生web组件到框架组件源码(二)
    从原生web组件到框架组件源码(一)
    拖拽滚动视图(一)
    SVG研究之路(一)下
    运算符
    编码
    格式化输出
    循环语句
    条件语句
    Python基础
  • 原文地址:https://www.cnblogs.com/lychnis/p/11681717.html
Copyright © 2011-2022 走看看