题解 | #牛群的合并#

牛群的合并

https://www.nowcoder.com/practice/d0cb24e1494e4f45a4b7d1a17db0daef

import java.util.*;

/*
 * public class ListNode {
 *   int val;
 *   ListNode next = null;
 *   public ListNode(int val) {
 *     this.val = val;
 *   }
 * }
 */

public class Solution {
    /**
     * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
     *
     * 
     * @param lists ListNode类一维数组 
     * @return ListNode类
     */
    public ListNode mergeKLists (ListNode[] lists) {
        // write code here
        if (lists == null || lists.length < 1) {
            return null;
        }
        int left = 0;
        int right = lists.length - 1;
        ListNode res = mergeK(lists, left, right);
        return res;
    }
    public ListNode mergeK(ListNode[] lists, int left, int right) {
        if (left == right) {
            return lists[left];
        }
        int mid = (left + right) / 2;
        ListNode l = mergeK(lists, left, mid);
        ListNode r = mergeK(lists, mid + 1, right);
        return merge(l,r);
    }
    // 合并两个链表
    public ListNode merge(ListNode left, ListNode right) {
        if (left == null) {
            return right;
        }
        if (right == null) {
            return left;
        }
        ListNode res = null;// 记录最后的头节点
        // 由于要求最后编号按升序排列,所以从左到右依次增大
        if (left.val <= right.val) {
            res = left;
            left = left.next;
        } else {
            res = right;
            right = right.next;
        }
        ListNode cur = res;
        while (left != null && right != null) {
            if (left.val >= right.val) {
                cur.next = right;
                right = right.next;
            } else {
                cur.next = left;
                left = left.next;
            }
            cur = cur.next;
        }
        while (left != null) {
            cur.next = left;
            cur = cur.next;
            left = left.next;
        }
        while (right != null) {
            cur.next = right;
            cur = cur.next;
            right = right.next;
        }
        return res;
    }
}

#归并排序##java##两个链表合并#
全部评论

相关推荐

11-11 14:21
西京学院 C++
Java抽象练习生:教育背景放最前面,不要耍小聪明
点赞 评论 收藏
分享
点赞 收藏 评论
分享
牛客网
牛客企业服务