题解 | 合并k个已排序的链表
合并k个已排序的链表
https://www.nowcoder.com/practice/65cfde9e5b9b4cf2b6bafa5f3ef33fa6
import java.util.*;
/*
* public class ListNode {
* int val;
* ListNode next = null;
* public ListNode(int val) {
* this.val = val;
* }
* }
*/
public class Solution {
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
*
* @param lists ListNode类ArrayList
* @return ListNode类
*/
public ListNode mergeKLists (ArrayList<ListNode> lists) {
// write code here
/**
* 思路分析:将list中所有值存放在List中,排序后 返回新的链表
*/
//1.将lists中所有val放到ArrayList中
ArrayList<Integer> list = new ArrayList<>();
for (ListNode listNode : lists) {
while(listNode != null){
list.add(listNode.val);
listNode = listNode.next;
}
}
//2.排序,sort,指定排序规则,从小到大
list.sort(new Comparator<Integer>() {
@Override
public int compare(Integer o1, Integer o2) {
return o1 - o2;
}
});
//3.新节点 + 新链表
ListNode dummyNode = new ListNode(-1);//虚拟节点
ListNode cur = dummyNode;
for (int i = 0; i < list.size(); i++) {
cur.next = new ListNode(list.get(i));
cur = cur.next;
}
return dummyNode.next;
}
}
查看19道真题和解析