leetcode:Merge k Sorted Lists 【Java】
2016-03-03 17:31
633 查看
一、问题描述
Merge k sorted
linked lists and return it as one sorted list. Analyze and describe its complexity.
二、问题分析
利用分治法,并结合算法Merge
Two Sorted Lists
三、算法代码
Merge k sorted
linked lists and return it as one sorted list. Analyze and describe its complexity.
二、问题分析
利用分治法,并结合算法Merge
Two Sorted Lists
三、算法代码
public class Solution { public ListNode mergeKLists(ListNode[] lists) { if(lists.length == 0){ return null; } return Sort(lists, 0, lists.length - 1); } public ListNode Sort(ListNode[] lists, int low, int high) {//利用分治思想排序 if (low < high) { int mid = low + (high - low) / 2; ListNode head1 = Sort(lists, low, mid); ListNode head2 = Sort(lists, mid + 1, high); return mergeTwoLists(head1, head2); } else return lists[low]; } public ListNode mergeTwoLists(ListNode l1, ListNode l2) { ListNode head = new ListNode(-1); ListNode cur = head; ListNode l1_index = l1; ListNode l2_index = l2; while(l1_index != null && l2_index != null){ if(l1_index.val >= l2_index.val){ cur.next = l2_index;//保持合并后的链表也是从小到大的顺序 cur = cur.next; l2_index = l2_index.next; }else{ cur.next = l1_index; cur = cur.next; l1_index = l1_index.next; } } if(l1_index != null){ cur.next = l1_index; } if(l2_index != null){ cur.next = l2_index; } return head.next; } }
相关文章推荐
- java 修改类注释
- java FutureTask
- java读取txt文件内容
- Java 入门 之 Thread 和 Runnable 类
- java搜索结果 通用result类
- Spring MVC 中 AJAX请求并返回JSON
- java 仓库maven
- 几种java远程调用通讯协议的比较
- Java基础学习总结——Java对象的序列化和反序列化
- 空格分割字符窜 java
- Java 入门 之 Synchronized 方法和块
- 【java学习笔记】对象数组初始化问题
- spring,springmvc 定时任务
- 【java学习笔记】for增强循环
- Java对象克隆——浅克隆和深克隆的区别
- 初识spring之quartz定时调度
- java 字符串缓冲池 String缓冲池
- java中compareTo和compare方法之比较
- JAVA虚拟机、Dalvik虚拟机和ART虚拟机简要对比
- Java线上应用故障排查之一:高CPU占用