问题:
Merge k sorted linked lists and return it as one sorted list. Analyze and describe its complexity.
问题要求:合并K个已经排好序的链表。
这个问题麻烦的地方在于:并没有定义链表排序的规则,即不知道升序还是降序。
同时链表的数量较多,判断和合并比较麻烦。
因此,最直观简便的做法,就是用空间换时间。
代码示例:
/** * Definition for singly-linked list. * public class ListNode { * int val; * ListNode next; * ListNode(int x) { val = x; } * } */
public class Solution {
public ListNode mergeKLists(ListNode[] lists) {
if (lists == null) {
return null;
}
//定义一个TreeMap,key为链表的值,value为值出现的次数
Map<Integer, Integer> valueWithNum = new TreeMap<>();
//轮询所有的链表,将值的信息加入到TreeMap
for (ListNode head : lists) {
while (head != null) {
if (valueWithNum.containsKey(head.val)) {
valueWithNum.put(head.val, valueWithNum.get(head.val) + 1);
} else {
valueWithNum.put(head.val, 1);
}
head = head.next;
}
}
ListNode temp = new ListNode(0);
ListNode result = temp;
//从TreeMap中重新构造出新的链表
for (Integer key : valueWithNum.keySet()) {
int num = valueWithNum.get(key);
while (num > 0) {
--num;
temp.next = new ListNode(key);
temp = temp.next;
}
}
return result.next;
}
}