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);
        }
    };
  • 相关阅读:
    C#+API实现指定窗体激活
    DEVC++学习之(一)
    javascript 实现原生下载的各种情况
    IssueVision 之WebService安全篇
    Add relationship to BS sample
    ExpandRelationWithCtxt 与 GetRelatedObjects 的区别
    C#调用javascript
    解禁网页限制
    Unix cc options vs gcc options
    IssueVision 之模式篇
  • 原文地址:https://www.cnblogs.com/aeipyuan/p/12638604.html
Copyright © 2011-2022 走看看