leetcode 23. Merge k Sorted Lists

Posted jamieliu

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了leetcode 23. Merge k Sorted Lists相关的知识,希望对你有一定的参考价值。

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

Example:

Input:
[
  1->4->5,
  1->3->4,
  2->6
]
Output: 1->1->2->3->4->4->5->6

 

采用优先级队列PriorityQueue,当对象add到queue中时,它已经按照某种排序方式(优先级)自动排序好了。

因此只需要从queue的头部开始取出元素,就是自动排好序的。

 

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
class Solution {
    public ListNode mergeKLists(ListNode[] lists) {
        if(lists == null || lists.length == 0) return null;
        PriorityQueue<ListNode> queue= new PriorityQueue<ListNode>(lists.length,new Comparator<ListNode>(){
           
            public int compare(ListNode o1, ListNode o2){
                if(o1.val < o2.val) {
                    return -1;
                }else if(o1.val == o2.val) {
                    return 0;
                }else {
                    return 1;
                }
            }
            
        });
        ListNode head = new ListNode(0);
        ListNode tail = head;
        for(int i=0;i<lists.length;i++){
            if(lists[i] != null) queue.add(lists[i]);
        }
        while(!queue.isEmpty()){
            tail.next = queue.poll();
            tail = tail.next;
            if(tail.next != null) {
                queue.add(tail.next);
            }
        }
        return head.next;
    }
}

 

以上是关于leetcode 23. Merge k Sorted Lists的主要内容,如果未能解决你的问题,请参考以下文章

[LeetCode] 23. Merge k Sorted Lists

[LeetCode] 23. Merge k Sorted Lists 合并k个有序链表

[LeetCode]23. Merge k Sorted Lists

leetcode23. Merge k Sorted Lists

leetCode 23. Merge k Sorted Lists

leetcode 23. Merge k Sorted Lists