首页 > 代码库 > 【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.
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 (归并排序)
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。