33. Merge k sorted linked lists

 

Title description

Merge \ k k sorted linked lists and return them as a sorted linked list. Analyze and describe its complexity. 

Example 1

enter

[{1,2,3},{4,5,6,7}]

return value

{1,2,3,4,5,6,7}

Code implementation :
 

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) {
 *         val = x;
 *         next = null;
 *     }
 * }
 */
import java.util.*;
public class Solution {
    public ListNode mergeKLists(ArrayList<ListNode> lists) {
         //优先字符,从小到大
        //重写比较器
        //特殊样例:输入:[[-2,-1,-1,-1],[]]
        if(lists.size() == 0) {
            return null;
        }
        Queue<ListNode> queue = new PriorityQueue( new Comparator<ListNode>() {
            public int compare(ListNode listNode1, ListNode listNode2) {
                return listNode1.val - listNode2.val;///重载优先级使其变为小根堆
            }
        });
        for(ListNode listNode : lists) {
            if(listNode == null) {
                continue;
            }
            queue.add(listNode);
        }
        ListNode head = new ListNode(0);
        ListNode tmp = head;
        while(queue.size() > 0) {
           tmp.next = queue.poll();
           tmp = tmp.next;
           if(tmp.next != null) {
               queue.add(tmp.next);
           }
        }
        return head.next;

    }
}

 

Guess you like

Origin blog.csdn.net/xiao__jia__jia/article/details/113470180