23:合并K个升序链表

This commit is contained in:
huangge1199@hotmail.com 2021-03-20 15:47:19 +08:00
parent be2995bb18
commit a6b01cf393
2 changed files with 97 additions and 1 deletions

View File

@ -0,0 +1,96 @@
//给你一个链表数组每个链表都已经按升序排列
//
// 请你将所有链表合并到一个升序链表中返回合并后的链表
//
//
//
// 示例 1
//
// 输入lists = [[1,4,5],[1,3,4],[2,6]]
//输出[1,1,2,3,4,4,5,6]
//解释链表数组如下
//[
// 1->4->5,
// 1->3->4,
// 2->6
//]
//将它们合并到一个有序链表中得到
//1->1->2->3->4->4->5->6
//
//
// 示例 2
//
// 输入lists = []
//输出[]
//
//
// 示例 3
//
// 输入lists = [[]]
//输出[]
//
//
//
//
// 提示
//
//
// k == lists.length
// 0 <= k <= 10^4
// 0 <= lists[i].length <= 500
// -10^4 <= lists[i][j] <= 10^4
// lists[i] 升序 排列
// lists[i].length 的总和不超过 10^4
//
// Related Topics 链表 分治算法
// 👍 1215 👎 0
package leetcode.editor.cn;
import com.code.leet.entiy.ListNode;
//23:合并K个升序链表
public class MergeKSortedLists{
public static void main(String[] args) {
//测试代码
Solution solution = new MergeKSortedLists().new Solution();
}
//力扣代码
//leetcode submit region begin(Prohibit modification and deletion)
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode() {}
* ListNode(int val) { this.val = val; }
* ListNode(int val, ListNode next) { this.val = val; this.next = next; }
* }
*/
class Solution {
public ListNode mergeKLists(ListNode[] lists) {
ListNode result = null;
for (int i = 0; i < lists.length; i++) {
result = mergeTwoLists(result,lists[i]);
}
return result;
}
public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
if (l1 == null) {
return l2;
}
if (l2 == null) {
return l1;
}
if (l1.val < l2.val) {
l1.next = mergeTwoLists(l1.next, l2);
return l1;
} else {
l2.next = mergeTwoLists(l1, l2.next);
return l2;
}
}
}
//leetcode submit region end(Prohibit modification and deletion)
}

File diff suppressed because one or more lines are too long