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)
    
    }
    
    
  • 相关阅读:
    你读了该博客中哪些超链接?有何感想
    最理想的师生关系是健身教练和学员的关系,在这种师生关系中你期望获得来自老师的哪些帮助?
    1500802028 王莉娟
    解码方法
    N皇后问题
    两个链表的交叉
    全排列
    交叉字符串
    翻转链表
    爬楼梯
  • 原文地址:https://www.cnblogs.com/xiaoshahai/p/13305699.html
Copyright © 2011-2022 走看看