23. Title leetcode merge sort list K

topic

K merge sort list, return the list sorted combined. Please complexity analysis and description of the algorithm.

Examples

Input:
[
1-> 4-> 5,
1-> 3-> 4,
2-> 6
]
Output: 1-> 1-> 2-> 3-> 4-> 4-> 5-> 6

General idea

The idea of ​​using divide and conquer.

First, look at the merger of the two lists,

Here Insert Picture Description
Every time we choose a smaller head element until the election last.

Next:

Here Insert Picture Description
Here Insert Picture Description
The following are omitted ...

The combined two lists codes

public ListNode mergeTwoLists(ListNode l1,ListNode l2){
		 if(l1==null) return l2;
		 if(l2==null) return l1;
		 if(l1.val<l2.val){
			 l1.next=mergeTwoLists(l1.next, l2);
			 return l1;
		 }else{
			 l2.next=mergeTwoLists(l1, l2.next);
			 return l2;
		 }
	 }

K Item merger

k-way merge, I believe that people learned a good understanding of data structures are merged thinking.
Here Insert Picture Description
Recursively merging using thought, first of all the elements into a single element, then sequentially combined, back up, most of a total combined total list. Divide and conquer is nothing more than two points and the process of governance, and rule of the process is actually merge.

Partition the code (including the above code)

public class problem23 {
	 //Definition for singly-linked list.
	 public static class ListNode {
	     int val;
	     ListNode next;
	     ListNode(int x) { val = x; }
	 }
	 public ListNode mergeKLists(ListNode[] lists) {
		 if(lists==null||lists.length==0) return null;//为空时的特判
		 return merge(lists,0,lists.length-1);
	 }
	 public ListNode merge(ListNode[] lists,int left,int right){
		 if(left==right) return lists[left];
		 int mid=left+(right-left)/2;
		 ListNode l1=merge(lists,left,mid);
		 ListNode l2=merge(lists,mid+1,right);
		 return mergeTwoLists(l1,l2);
	 }
	 public ListNode mergeTwoLists(ListNode l1,ListNode l2){
		 if(l1==null) return l2;
		 if(l2==null) return l1;
		 if(l1.val<l2.val){
			 l1.next=mergeTwoLists(l1.next, l2);
			 return l1;
		 }else{
			 l2.next=mergeTwoLists(l1, l2.next);
			 return l2;
		 }
	 }
}

Published 15 original articles · won praise 0 · Views 180

Guess you like

Origin blog.csdn.net/qq_36360463/article/details/103988716