Shawngbk / Leecode

Questions of Leecode
0 stars 0 forks source link

23. Merge k Sorted Lists #27

Open Shawngbk opened 8 years ago

Shawngbk commented 8 years ago

与21题相关,就是运用merge排序来做。

D daniel123 Reputation: 2 minHeap: time - O(nlog(k)), space - O(k), n is total number of all the listnode, k is the length of lists

public ListNode mergeKLists(ListNode[] lists) { if (lists == null || lists.length == 0) { return null; } return heap(lists); } private ListNode heap(ListNode[] lists) { PriorityQueue pq = new PriorityQueue<>(new Comparator() { public int compare(ListNode a, ListNode b) { return a.val - b.val; } }); for (ListNode head : lists) { if (head != null) pq.offer(head); } ListNode res = new ListNode(0); ListNode resHead = res; while (!pq.isEmpty()) { ListNode cur = pq.poll(); res.next = cur; res = res.next; if (cur.next != null) { pq.offer(cur.next); } } return resHead.next; }

like mergeSort(recursion): time-O(vlog(k)), space- O(log(k)), v is average length of a list, k is length of lists

/**

Shawngbk commented 8 years ago