zoukankan      html  css  js  c++  java
  • leetCode 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

    采用分治算法,时间复杂度为nlog(n),同分治排序。

     1 /**
     2  * Definition for singly-linked list.
     3  * public class ListNode {
     4  *     int val;
     5  *     ListNode next;
     6  *     ListNode(int x) { val = x; }
     7  * }
     8  */
     9 class Solution {
    10     //返回lists数组第low至high位置(不包括high位置)的链表merge后的链表
    11     public ListNode result(ListNode[] lists,int low,int high){
    12         if (low+1==high) return lists[low];
    13         int mid=(low+high)/2;
    14         ListNode left = result(lists,low,mid);
    15         ListNode right = result(lists,mid,high);
    16 
    17         //merge left链表和right链表
    18         ListNode head = new ListNode(-65535);
    19         ListNode p = head;//指向head最后一个节点
    20         while (left!=null && right!=null){
    21             if (left.val < right.val){
    22                 p.next=left;
    23                 left=left.next;
    24             }else {
    25                 p.next=right;
    26                 right=right.next;
    27             }
    28             p=p.next;
    29         }
    30         if (left!=null){
    31             p.next=left;
    32         }
    33         if (right!=null){
    34             p.next=right;
    35         }
    36         return head.next;
    37     }
    38 
    39     public ListNode mergeKLists(ListNode[] lists) {
    40         if (lists.length==0) return null;
    41         if (lists.length==1) return lists[0];
    42         ListNode result = result(lists, 0, lists.length);
    43         return result;
    44     }
    45 }
  • 相关阅读:
    新版open live writer连接博客园
    github个人博客域名绑定(附带详细原理说明)
    开源性能监控分析工具glowroot
    (转)Python实例手册
    Jetty嵌入式Web容器攻略
    H2数据库攻略
    CAS ticket过期策略
    CAS自定义登录验证方法
    Sonatype Nexus高级配置
    配置sonar、jenkins进行持续审查
  • 原文地址:https://www.cnblogs.com/yfs123456/p/10983085.html
Copyright © 2011-2022 走看看