首页 > 其他 > 详细

Merge k Sorted Lists

时间:2015-06-04 02:06:51      阅读:244      评论:0      收藏:0      [点我收藏+]

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

?

/**
 * 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 (lists==null || lists.length==0) {
        	return null;
        }
        PriorityQueue<ListNode> queue = new PriorityQueue<ListNode>(lists.length, new Comparator<ListNode>() {

			@Override
			public int compare(ListNode o1, ListNode o2) {
				if (o1.val < o2.val) {
					return -1;
				} else if (o1.val > o2.val) {
					return 1;
				} else {
					return 0;
				}
			}
		});
        for (ListNode list : lists) {
        	if (list == null) {
        		continue;
        	}
        	queue.add(list);
        }
        ListNode head = new ListNode(0);
        ListNode curNode = head;
        while (!queue.isEmpty()) {
        	ListNode t = queue.poll();
    		curNode.next = t;
        	curNode = t;
        	if (t.next != null) {
        		queue.add(t.next);
        	}
        }
        return head.next;
    }
}

?

Merge k Sorted Lists

原文:http://hcx2013.iteye.com/blog/2216801

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!