标签:
题目地址:https://leetcode.com/problems/merge-k-sorted-lists/
题目解析:采用二分归并法,将链表分为两部分,两部分合并后再将结果合并;对其中的每一部分的合并采用递归的方法进行。
题目解答:
/** * 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) { if(lists == null || lists.size() == 0){ return null; } return mergeKLists(lists,0,lists.size() - 1); } private ListNode mergeKLists(List<ListNode> lists,int start,int end){ if(start == end){ return lists.get(start); } if((end - start) == 1){ return mergeTwoLists(lists.get(start),lists.get(end)); } ListNode left = mergeKLists(lists,start,(start+end)/2); ListNode right = mergeKLists(lists,(start+end)/2+1,end); return mergeTwoLists(left,right); } private ListNode mergeTwoLists(ListNode first,ListNode second){ if(first == null){ return second; } if(second == null){ return first; } ListNode ret = null; if(first.val <= second.val){ ret = first; first = first.next; }else{ ret = second; second = second.next; } ListNode insert = ret; while(first!=null && second!=null){ if(first.val <= second.val){ insert.next = first; first = first.next; }else{ insert.next = second; second = second.next; } insert = insert.next; insert.next= null; } insert.next = (first == null ? second:first); return ret; } }
标签:
原文地址:http://www.cnblogs.com/xiongyuesen/p/4433638.html