• 144669

    文章

  • 854

    评论

  • 13

    友链

  • 最近新加了换肤功能,大家多来逛逛吧~~~~
  • 喜欢这个网站的朋友可以加一下QQ群,我们一起交流技术。

LeetCode - Hard - 23. Merge k Sorted Lists


Topic

  • Linked List
  • Divide and Conquer
  • Heap

Description

https://leetcode.com/problems/merge-k-sorted-lists/

You are given an array of k linked-lists lists, each linked-list is sorted in ascending order.

Merge all the linked-lists into one sorted linked-list and return it.

Example 1:

Input: lists = [[1,4,5],[1,3,4],[2,6]]
Output: [1,1,2,3,4,4,5,6]
Explanation: The linked-lists are:
[
  1->4->5,
  1->3->4,
  2->6
]
merging them into one sorted list:
1->1->2->3->4->4->5->6

Example 2:

Input: lists = []
Output: []

Example 3:

Input: lists = [[]]
Output: []

Constraints:

  • k == lists.length
  • 0 <= k <= 10^4
  • 0 <= lists[i].length <= 500
  • -10^4 <= lists[i][j] <= 10^4
  • lists[i] is sorted in ascending order.
  • The sum of lists[i].length won't exceed 10^4.

Analysis

LeetCode 21. Merge Two Sorted Lists的延伸。

Submission

import com.lun.util.SinglyLinkedList.ListNode;

public class MergeKSortedLists {

	public ListNode mergeKLists(ListNode[] lists) {
		ListNode result = null;
		if (lists == null)
			return result;

		for (ListNode list : lists) {
			result = mergeTwoList(result, list);
		}

		return result;
	}

	private ListNode mergeTwoList(ListNode l1, ListNode l2) {
		if (l1 == null) {
			return l2;
		} else if (l2 == null) {
			return l1;
		} else if (l1.val < l2.val) {
			l1.next = mergeTwoList(l1.next, l2);
			return l1;
		} else {
			l2.next = mergeTwoList(l1, l2.next);
			return l2;
		}
	}

}

Test

import static org.junit.Assert.*;
import static com.lun.util.SinglyLinkedList.*;

import org.junit.Test;

import com.lun.util.SinglyLinkedList.ListNode;

public class MergeKSortedListsTest {

	@Test
	public void test() {
		MergeKSortedLists obj = new MergeKSortedLists();

		ListNode[] lists1 = {ints2List(1, 4, 5), ints2List(1, 3, 4), ints2List(2, 6)};
		ListNode expected1 = ints2List(1, 1, 2, 3, 4, 4, 5, 6);
		
		assertTrue(areTwoListEqual(obj.mergeKLists(lists1), expected1));
		
		ListNode[] list2 = null;
		assertNull(obj.mergeKLists(list2));
		
		ListNode[] list3 = {};
		assertNull(obj.mergeKLists(list3));
	}
}

695856371Web网页设计师②群 | 喜欢本站的朋友可以收藏本站,或者加入我们大家一起来交流技术!

0条评论

Loading...


发表评论

电子邮件地址不会被公开。 必填项已用*标注

自定义皮肤 主体内容背景
打开支付宝扫码付款购买视频教程
遇到问题联系客服QQ:419400980
注册梁钟霖个人博客