Merge k sorted linked lists and return it as one sorted list. Analyze and describe its complexity.
题目:把k个有序的链表合并成一个新的链表。
思路:采用合并两个链表的方法,把K个链表的值都取出来放到list里面,排序后创建新的链表。
public class Solution {
public ListNode mergeKLists(ListNode[] lists) {
ListNode newNode = new ListNode(0);
ListNode head = newNode;
List<Integer> list = new ArrayList<Integer>();
for(int i = 0; i < lists.length;i++) {
while(lists[i] != null) {
list.add(lists[i].val);
lists[i] = lists[i].next;
}
}
Collections.sort(list);
for(Integer integer : list) {
ListNode n = new ListNode(integer);
head.next = n;
head = head.next;
}
return newNode.next;
}
}

546

被折叠的 条评论
为什么被折叠?



