码迷,mamicode.com
首页 > 其他好文 > 详细

LeetCode | # 23

时间:2015-03-09 22:32:10      阅读:203      评论:0      收藏:0      [点我收藏+]

标签:

题目:

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

思路:

  • 解法一:维护一个大小为k的堆,每次去堆顶的最小元素放到结果中,然后读取该元素的下一个元素放入堆中,重新维护好。因为每个链表是有序的,每次又是去当前k个元素中最小的,所以当所有链表都读完时结束,这个时候所有元素按从小到大放在结果链表中。其实是用到Java的优先级队列PriorityQueue,定义自己的Comparator来改变排序规则。
/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) {
 *         val = x;
 *         next = null;
 *     }
 * }
 */
public class Solution {
    public ListNode mergeKLists(List<ListNode> lists) {
        int k = lists.size();
        if(k==0)return null;
		PriorityQueue<ListNode> heap = new PriorityQueue<ListNode>(
				k, new Comparator<ListNode>(){
					@Override
					public int compare(ListNode o1, ListNode o2) {
						return o1.val-o2.val;
					}
				});
		for(int i=0; i<k; i++){
			ListNode node = lists.get(i);
			if(node != null){
				heap.offer(node);
			}
		}
		ListNode head = new ListNode(0), pre = head;
		while(heap.size()>0){
			ListNode c = heap.poll();
			pre.next = c;
			pre = pre.next;
			if(c.next != null)
				heap.offer(c.next);
		}
		return head.next;
    }
}


LeetCode | # 23

标签:

原文地址:http://blog.csdn.net/allhaillouis/article/details/44160175

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!