zoukankan      html  css  js  c++  java
  • 链表合并 leetcode

    23. 合并K个排序链表

    难度困难539

    合并 个排序链表,返回合并后的排序链表。请分析和描述算法的复杂度。

    示例:

    输入:
    [
      1->4->5,
      1->3->4,
      2->6
    ]
    输出: 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* merge2(ListNode* l1,ListNode* l2){
            /*---------递归法---------*/
            if(!l1||!l2)    return l1?l1:l2;
            if((*l1).val<(*l2).val){
                l1->next=merge2(l1->next,l2);
                return l1;
            }else{
                l2->next=merge2(l1,l2->next);
                return l2;
            }
            /*---------循环法---------*/
            // if(!l1||!l2)    return l1?l1:l2;
            // ListNode* head=new ListNode(0);
            // ListNode* m=head;
            // ListNode* x=l1; 
            // ListNode* y=l2;
            // while(x&&y){
            //     if((*x).val<(*y).val){
            //         m->next=x;
            //         x=x->next;
            //     }else{
            //         m->next=y;
            //         y=y->next;
            //     }
            //     m=m->next;
            // }
            // m->next=x?x:y;
            // return head->next;
        }
        ListNode* mergeList(vector<ListNode*>& lists,int x,int y){
            if(y<x)  return NULL;
            if(y==x) return lists[y];
            //二分
            int m=(x+y)/2;
            return merge2(mergeList(lists,x,m),mergeList(lists,m+1,y));
        }
        ListNode* mergeKLists(vector<ListNode*>& lists) {
            int len=lists.size();
            if(!lists.size())   return NULL;
            return mergeList(lists,0,len-1);
        }
    };
  • 相关阅读:
    前端知识之JavaScript内容(一)
    前端2css层叠样式表
    前端:html初识以及标签
    css
    python--re模块(正则表达式)
    python--xml模块
    关于导包问题
    前端浅了解
    试写仿优酷系统坑点
    sqlalchemy
  • 原文地址:https://www.cnblogs.com/aeipyuan/p/12638604.html
Copyright © 2011-2022 走看看