LeetCode——Merge k Sorted Lists

时间:2023-03-09 16:51:18
LeetCode——Merge k Sorted Lists

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