23. Merge k Sorted Lists

来源:互联网 发布:石榴算法 编辑:程序博客网 时间:2024/06/03 21:15

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

Subscribe to see which companies asked this question.


Solution:

Tips:

leverage priority queue of java.


Java Code:

/** * 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 (null == lists || lists.length < 1) {            return null;        }        if (1 == lists.length) {            return lists[0];        }                //PriorityQueue        ListNode head = new ListNode(0);        ListNode tail = head;        PriorityQueue<ListNode> queue= new PriorityQueue<>(new Comparator<ListNode>(){            @Override            public int compare(ListNode o1,ListNode o2){                return o1.val - o2.val;            }        });                // init queue        for (int i = 0; i < lists.length; i++) {            if (lists[i] != null) {                ListNode tmp = lists[i];                while (tmp != null) {                    // add() or offer(), previous one throws exception, the rear one return false when met failure.                    queue.offer(tmp);                    tmp = tmp.next;                }            }        }                // get element one by one        while (!queue.isEmpty()){            // remove() or poll() previous one throws exception, the rear one return false when met failure.            tail.next = queue.poll();            tail = tail.next;            tail.next = null;        }                return head.next;    }}


0 0
原创粉丝点击