[LeetCode] Merge K Sorted Lists
Merge k sorted linked lists and return it as one sorted list. Analyze and describe its complexity.
时间复杂度 O(nlogk)
思路:
这道题其实有三种做法,第一种是priorityQueue,第二种是Divided & Conquer, 第三种是两两并归。每一种都很重要,需要多多联系。
第一种, priorityQueue
/** * 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; ListNode dummy = new ListNode(0); ListNode head = dummy; PriorityQueue<ListNode> q = new PriorityQueue<>(lists.length, new Comparator<ListNode>(){ public int compare(ListNode l1, ListNode l2) { return l1.val - l2.val; } }); for (ListNode list : lists) { if (list != null) { q.offer(list); } } while (!q.isEmpty()) { ListNode tmp = q.poll(); head.next = tmp; if (tmp.next != null) { q.offer(tmp.next); } head = head.next; } return dummy.next; } }
posted on 2018-03-27 09:02 codingEskimo 阅读(101) 评论(0) 编辑 收藏 举报