Java:合并K个排序链表

//合并 k 个排序链表,返回合并后的排序链表。请分析和描述算法的复杂度。 
//
// 示例: 
//
// 输入:
//[
//  1->4->5,
//  1->3->4,
//  2->6
//]
//输出: 1->1->2->3->4->4->5->6 
// Related Topics 堆 链表 分治算法

package leetcode.editor.cn;

//Java:合并K个排序链表
public class P23MergeKSortedLists {
    public static void main(String[] args) {
        Solution solution = new P23MergeKSortedLists().new Solution();
        // TO TEST
        ListNode listNode1_1 = new ListNode(1);
        ListNode listNode1_2 = new ListNode(4);
        ListNode listNode1_3 = new ListNode(5);
        listNode1_1.next = listNode1_2;
        listNode1_2.next = listNode1_3;
        ListNode listNode2_1 = new ListNode(1);
        ListNode listNode2_2 = new ListNode(3);
        ListNode listNode2_3 = new ListNode(4);
        listNode2_1.next = listNode2_2;
        listNode2_2.next = listNode2_3;
        ListNode listNode3_1 = new ListNode(2);
        ListNode listNode3_2 = new ListNode(6);
        listNode3_1.next = listNode3_2;
        //
        System.out.println(solution.mergeKLists(new ListNode[]{listNode1_1, listNode2_1, listNode3_1}));
    }
    //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) {
            int length = lists.length;
            if (lists == null || length < 1) {
                return null;
            } else if (length == 1) {
                return lists[0];
            }
            ListNode result = null;
            ListNode min;
            ListNode pointResult = null;
            int pointX;
            while (true) {
                min = null;
                pointX = 0;
                for (int x = 0; x < length; x++) {
                    if (lists[x] != null) {
                        if (min == null || (lists[x].val < min.val)) {
                            pointX = x;
                            min = lists[x];
                        }
                    }
                }
                if (min == null) {
                    break;
                }
                lists[pointX] = min.next;
                if (result == null) {
                    result = new ListNode(min.val);
                    pointResult = result;
                } else {
                    pointResult.next = new ListNode(min.val);
                    pointResult = pointResult.next;
                }
            }
            return result;
        }
    }
//leetcode submit region end(Prohibit modification and deletion)

}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值