企业网站建设费详细的营销推广方案
我:爷爷,我想用递归写这道题。爷爷给了我最爱吃的大嘴巴子
题目:
合并 k 个排序链表,返回合并后的排序链表。请分析和描述算法的复杂度。
示例:
输入:
[
1->4->5,
1->3->4,
2->6
]
输出: 1->1->2->3->4->4->5->6
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/merge-k-sorted-lists
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
代码:
/*** Definition for singly-linked list.* public class ListNode {* int val;* ListNode next;* ListNode(int x) { val = x; }* }*/
class Solution {public ListNode mergeKLists(ListNode[] lists) {int nullcount=0;if(lists.length==0)return null;for(int i=0;i<lists.length;i++){if(lists[i]==null)nullcount++;}if(nullcount==lists.length)return null;List<ListNode> list=new ArrayList<>();for(int i=0;i<lists.length;i++){ListNode tempNode=lists[i];while(tempNode!=null){list.add(tempNode);tempNode=tempNode.next;}}Collections.sort(list,new Comparator<ListNode>() {@Overridepublic int compare(ListNode o1, ListNode o2) {// TODO Auto-generated method stubreturn o1.val-o2.val;}});ListNode work=list.get(0);for(int i=0;i<list.size()-1;i++){work.next=list.get(i+1);work=work.next;}return list.get(0);}
}