首页 > 代码库 > 【leetcode】Merge k Sorted Lists (归并排序)

【leetcode】Merge k Sorted Lists (归并排序)

题目:

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

解析:合并k个有序链表,最后返回一个总的有序链表,分析并描述其复杂度。该题的实质为归并排序,平均时间复杂度为O(NlogN)。

Java AC代码:

public class Solution {

	public ListNode mergeKLists(List<ListNode> lists) {
		if(lists==null || lists.size()==0){
			return null;
		}
		return recursion(lists,0,lists.size()-1);
	}
	
	public ListNode recursion(List<ListNode> lists,int start,int end){
		if(start<end){
			int center = (start+end)/2;
			return merge(recursion(lists,start,center),recursion(lists,center+1,end));
		}
		return lists.get(start);
	}
	
	public ListNode merge(ListNode node1,ListNode node2){
		ListNode result = new ListNode(0);
		ListNode head = result;
		while(node1!=null && node2!=null){
			if(node1.val<node2.val){
				result.next = node1;
				node1 = node1.next;
			}else{
				result.next = node2;
				node2 = node2.next;
			}
			result = result.next;
		}
		while(node1!=null){
			result.next = node1;
			result = result.next;
			node1 = node1.next;
		}
		while(node2!=null){
			result.next = node2;
			result = result.next;
			node2 = node2.next;
		}
		return head.next;
	}

}


【leetcode】Merge k Sorted Lists (归并排序)