标签:leetcode scribe lis for new color lse 就是 lex
Merge k sorted linked lists and return it as one sorted list. Analyze and describe its complexity.
Example:
Input: [ 1->4->5, 1->3->4, 2->6 ] Output: 1->1->2->3->4->4->5->6
采用优先级队列PriorityQueue,当对象add到queue中时,它已经按照某种排序方式(优先级)自动排序好了。
因此只需要从queue的头部开始取出元素,就是自动排好序的。
/** * 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; PriorityQueue<ListNode> queue= new PriorityQueue<ListNode>(lists.length,new Comparator<ListNode>(){ public int compare(ListNode o1, ListNode o2){ if(o1.val < o2.val) { return -1; }else if(o1.val == o2.val) { return 0; }else { return 1; } } }); ListNode head = new ListNode(0); ListNode tail = head; for(int i=0;i<lists.length;i++){ if(lists[i] != null) queue.add(lists[i]); } while(!queue.isEmpty()){ tail.next = queue.poll(); tail = tail.next; if(tail.next != null) { queue.add(tail.next); } } return head.next; } }
leetcode 23. Merge k Sorted Lists
标签:leetcode scribe lis for new color lse 就是 lex
原文地址:https://www.cnblogs.com/jamieliu/p/10328283.html