zoukankan      html  css  js  c++  java
  • Lc23_合并K个排序链表

    //合并 k 个排序链表,返回合并后的排序链表。请分析和描述算法的复杂度。 
    //
    // 示例: 
    //
    // 输入:
    //[
    //  1->4->5,
    //  1->3->4,
    //  2->6
    //]
    //输出: 1->1->2->3->4->4->5->6 
    // Related Topics 堆 链表 分治算法
    
    package leetcode.editor.cn;
    
    import com.example.demo.ListNode;
    
    //Java:合并K个排序链表
    public class P23MergeKSortedLists{
        public static void main(String[] args) {
            Solution solution = new P23MergeKSortedLists().new Solution();
            // TO TEST
        }
        //leetcode submit region begin(Prohibit modification and deletion)
    /**
     * Definition for singly-linked list.
     * public class ListNode {
     *     int val;
     *     ListNode next;
     *     ListNode(int x) { val = x; }
     * }
     */
    class Solution {
        public ListNode mergeKLists(ListNode[] lists) {
            ListNode res = null;
            for (int i = 0; i < lists.length; i++) {
                res =  merge(res,lists[i]);
            }
            return res;
    
        }
    
        //依次合并链表
        private ListNode merge(ListNode l1, ListNode l2){
            if(l1==null){
                return l2;
            }
    
            if(l2==null){
                return l1;
            }
    
            if(l1.val<l2.val){
               l1.next = merge(l1.next,l2);
               return l1;
            }else{
              l2.next =merge(l1,l2.next);
              return l2;
            }
        }
    }
    //leetcode submit region end(Prohibit modification and deletion)
    
    }
    
    
  • 相关阅读:
    所有程序员都是自学成才
    Xcode6模拟器路径
    Xcode7中模拟器的位置
    数据结构中的二级指针和引用
    02_线性表的链式表示和实现
    Spring 单例 httprequest 线程安全
    Springboot listener
    Spring单例 和 Scope注解
    红黑树
    线程池
  • 原文地址:https://www.cnblogs.com/xiaoshahai/p/13305699.html
Copyright © 2011-2022 走看看