关闭

【LeetCode】 023. Merge k Sorted Lists

78人阅读 评论(0) 收藏 举报
分类:

Merge k sorted linked lists and return it as one sorted list. Analyze and describe its complexity.

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
public class Solution {
    public ListNode mergeKLists(ListNode[] lists) {
        if (lists.length == 0) {
            return null;
        }
        PriorityQueue<ListNode> list = new PriorityQueue<ListNode>(new Comparator<ListNode>() {
            @Override
            public int compare(ListNode n1, ListNode n2) {
                return n1.val - n2.val;
            }
        });
        ListNode temp = new ListNode(0);
        ListNode res = temp;
        for (ListNode subList : lists) {
            if (subList != null) {
                list.add(subList);
            }
        }
        while (!list.isEmpty()) {
            temp.next = list.poll();
            temp = temp.next;
            if (temp.next != null) {
                list.add(temp.next);
            }
        }
        return res.next;
    }
}


0
0

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:18097次
    • 积分:2311
    • 等级:
    • 排名:第16756名
    • 原创:240篇
    • 转载:0篇
    • 译文:0篇
    • 评论:0条
    文章分类