首页 技术 正文
技术 2022年11月14日
0 收藏 528 点赞 3,190 浏览 1165 个字

Discription:

Merge k sorted linked lists and return it as one sorted list. Analyze and describe its complexity.

Subscribe to see which companies asked this question.

思路:其实就是归并排序的最后一步归并操作。思想是递归分治,先把一个大问题分成2个子问题,然后对2个子问题的解进行合并。经过一次遍历就能找出已经有序的序列。就算是题目中给出的条件,已经有K个已经排好序的链表。然后递归的把问题分成2个,4个。。。。logK个子序列。然后每两个子序列的解进行合并。最后得到一个排好序的链表。时间复杂度为O(nlogK)。

代码:

/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
public class Solution { public ListNode merge2Lists(ListNode list1, ListNode list2) { ListNode head = new ListNode(0);
ListNode cur = head; while(list1 != null && list2 != null) {
if(list1.val < list2.val) {
cur.next = list1;
list1 = list1.next;
}
else {
cur.next = list2;
list2 = list2.next;
}
cur = cur.next;
} while(list1 != null) {
cur.next = list1;
list1 = list1.next;
cur = cur.next;
} while(list2 != null) {
cur.next = list2;
list2 = list2.next;
cur = cur.next;
} return head.next;
} public ListNode mergeKLists(ListNode[] lists) { if(lists == null || lists.length == 0) {
return null;
} if(lists.length == 1) {
return lists[0];
} int mid = lists.length / 2; ListNode list1 = mergeKLists(Arrays.copyOfRange(lists, 0, mid));
ListNode list2 = mergeKLists(Arrays.copyOfRange(lists, mid, lists.length)); return merge2Lists(list1, list2);
}
}

为何这道题Java的效率这么高,把C/C++都完爆了。

LeetCode——Merge k Sorted Lists

相关推荐
python开发_常用的python模块及安装方法
adodb:我们领导推荐的数据库连接组件bsddb3:BerkeleyDB的连接组件Cheetah-1.0:我比较喜欢这个版本的cheeta…
日期:2022-11-24 点赞:878 阅读:9,031
Educational Codeforces Round 11 C. Hard Process 二分
C. Hard Process题目连接:http://www.codeforces.com/contest/660/problem/CDes…
日期:2022-11-24 点赞:807 阅读:5,520
下载Ubuntn 17.04 内核源代码
zengkefu@server1:/usr/src$ uname -aLinux server1 4.10.0-19-generic #21…
日期:2022-11-24 点赞:569 阅读:6,368
可用Active Desktop Calendar V7.86 注册码序列号
可用Active Desktop Calendar V7.86 注册码序列号Name: www.greendown.cn Code: &nb…
日期:2022-11-24 点赞:733 阅读:6,148
Android调用系统相机、自定义相机、处理大图片
Android调用系统相机和自定义相机实例本博文主要是介绍了android上使用相机进行拍照并显示的两种方式,并且由于涉及到要把拍到的照片显…
日期:2022-11-24 点赞:512 阅读:7,781
Struts的使用
一、Struts2的获取  Struts的官方网站为:http://struts.apache.org/  下载完Struts2的jar包,…
日期:2022-11-24 点赞:671 阅读:4,862