이름
K 병합 정렬 목록, 목록이 결합 된 소트 돌아갑니다. 제발 복잡도 분석 및 알고리즘의 설명입니다.
예
입력 :
[
1-> 4 -> 5,
1-> 3-> 4,
2-> 6
]
출력 : 1-> 1-> 2-> 3-> 4 -> 4-> 5-> 6
일반 아이디어
분할 및 정복을 사용하는 아이디어.
첫째, 두 목록의 합병 봐,
때마다 우리는 지난 선거 때까지 작은 헤드 요소를 선택합니다.
다음 :
다음은 생략 ...
결합 된 두 개의 목록 코드
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 항목 합병
K-방법 병합, 나는 사람들이 데이터 구조의 이해 좋은되어 병합 생각을 배웠다고 생각합니다.
재귀 제 단일 요소로 모든 요소의 순차적 백업 결합 사상을 이용하여 전체리스트를 결합 된 전체의 대부분을 병합. 분할 및 정복 실제로 병합 된 프로세스를보다 두 지점 이상 아무것도 및 관리의 프로세스 및 규칙입니다.
(위의 코드 포함) 코드를 분할
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;
}
}
}