• 23. 合并K个升序链表


    23. 合并K个升序链表

    思路:

      将两个有序链表合并,推广到n个链表的合并,就是将n个链表两两合并,再合并,就是归并排序的思维,现将数组递归到单个元素终止,然后执行两两merge。

    https://leetcode-cn.com/problems/merge-k-sorted-lists/solution/he-bing-kge-pai-xu-lian-biao-by-leetcode-solutio-2/

    /**
     * Definition for singly-linked list.
     * public class ListNode {
     *     int val;
     *     ListNode next;
     *     ListNode() {}
     *     ListNode(int val) { this.val = val; }
     *     ListNode(int val, ListNode next) { this.val = val; this.next = next; }
     * }
     */
    class Solution {
    public ListNode mergeKLists(ListNode[] lists) {
            if (lists == null || lists.length == 0) {
                return null;
            }
            return merge(lists, 0, lists.length - 1);
        }
    
        public ListNode merge(ListNode[] lists, int l, int r) {
            if (l == r) {
                return lists[l];
            }
            if (l > r) {
                return null;
            }
            int mid = (l + r) >> 1;
            return mergeTwoListNode(merge(lists, l, mid), merge(lists, mid + 1, r));
        }
    
        // 合并两个链表
        public ListNode mergeTwoListNode(ListNode listNode1, ListNode listNode2) {
            ListNode head = new ListNode(-1);
            ListNode result=head;
            while (listNode1 != null && listNode2 != null) {
                if(listNode1.val<listNode2.val){
                    result.next=listNode1;
                    listNode1=listNode1.next;
                }else {
                    result.next=listNode2;
                    listNode2=listNode2.next;
                }
                result=result.next;
            }
            if(listNode1!=null){
                result.next=listNode1;
            }else {
                result.next=listNode2;
            }
            return head.next;
        }
    }

    。。

  • 相关阅读:
    函数传参-修改文本
    函数传参-商品计价
    嵌套选项卡自动播放
    仿淘宝自动播放菜单栏
    仿淘宝侧边栏菜单
    图片自动切换
    定时器应用-页面弹出广告
    转:Java面试题集(1-50)
    转:115个Java面试题和答案——终极列表(上)
    毕向东day01笔记--dos-jdk-jre-环境变量等
  • 原文地址:https://www.cnblogs.com/guoyu1/p/15716728.html
Copyright © 2020-2023  润新知