Java教程

23. Merge k Sorted Lists 合并k个排序链表

本文主要是介绍23. Merge k Sorted Lists 合并k个排序链表,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

You are given an array of k linked-lists lists, each linked-list is sorted in ascending order.

Merge all the linked-lists into one sorted linked-list and return it.

 

Example 1:

Input: lists = [[1,4,5],[1,3,4],[2,6]]
Output: [1,1,2,3,4,4,5,6]
Explanation: The linked-lists are:
[
  1->4->5,
  1->3->4,
  2->6
]
merging them into one sorted list:
1->1->2->3->4->4->5->6

Example 2:

Input: lists = []
Output: []

Example 3:

Input: lists = [[]]
Output: []

就是用q啊

/**
 * Definition for ListNode.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int val) {
 *         this.val = val;
 *         this.next = null;
 *     }
 * }
 */ 
public class Solution {
    /**
     * @param lists: a list of ListNode
     * @return: The head of one sorted list.
     */
      //comparator
     private Comparator<ListNode> ListNodeComparator = new Comparator<ListNode>() {
           public int compare(ListNode left, ListNode right) {
               return left.val - right.val;
           }
       };
       
    public ListNode mergeKLists(ListNode[] lists) {  
        //new heap
        if (lists.length == 0 || lists == null) {
            return null;
        }
        
       Queue<ListNode> heap = new PriorityQueue<ListNode>(lists.length,ListNodeComparator);
       for (int i = 0; i < lists.length; i++) {
           if (lists[i] != null) {
               //先加每个的head,1 1 2,然后小的才有资格继续加 4 3
               //加进来之后一起去和2比较,2更小,然后继续加
               //把整个的list加进去
               heap.add(lists[i]);
           }
       }
        //add to the lists
        ListNode dummy = new ListNode(0);
        ListNode tail = dummy;
        while(!heap.isEmpty()) {
            ListNode head = heap.poll();
            System.out.println("head = " + head.val);
            tail.next = head;
            tail = head;
            
            if (head.next != null) {
                System.out.println("添加的head.next = " + head.next.val);
                 System.out.println("  ");
                heap.add(head.next);
            }
        }
        return dummy.next;
    }
}

 

 
这篇关于23. Merge k Sorted Lists 合并k个排序链表的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!