[LeetCode] 23. 合并K个排序链表
一开始想到的方法一看官方解答好像很慢。。。。。
看了精选答案:
/** * Definition for singly-linked list. * public class ListNode { * int val; * ListNode next; * ListNode(int x) { val = x; } * } */ class Solution { public ListNode mergeKLists(ListNode[] lists) { if(lists==null||lists.length==0) return null; PriorityQueue<ListNode> queue=new PriorityQueue<>(lists.length, new Comparator<ListNode>() { @Override public int compare(ListNode o1, ListNode o2) { if(o1.val-o2.val<0)return -1; else if(o1.val==o2.val)return 0; else return 1; } }); ListNode dummpy=new ListNode(0); ListNode p=dummpy; for(ListNode node:lists){ if(node!=null) queue.add(node); } while(!queue.isEmpty()){ p.next=queue.poll(); p=p.next; if(p.next!=null) queue.add(p.next); } return dummpy.next; } }
更快的是merge
/** * Definition for singly-linked list. * public class ListNode { * int val; * ListNode next; * ListNode(int x) { val = x; } * } */ class Solution { public ListNode mergeKLists(ListNode[] lists) { ListNode newHead = null; if(lists == null || lists.length == 0){ return newHead; } int size = lists.length; if(size <= 1){ return lists[0]; } if(size <= 2){ ListNode src1 = lists[0]; ListNode src2 = lists[1]; return mergeList(src1,src2); }else{ int lengthLow = size / 2; int lengthHig = size - lengthLow; ListNode[] listLeft = new ListNode[lengthLow]; ListNode[] listRigth = new ListNode[lengthHig]; System.arraycopy(lists,0,listLeft,0,lengthLow); System.arraycopy(lists,lengthLow,listRigth,0,lengthHig); ListNode leftNode = mergeKLists(listLeft); ListNode rightNode = mergeKLists(listRigth); return mergeList(leftNode,rightNode); } } public ListNode mergeList(ListNode src1,ListNode src2){ ListNode node = null; ListNode newHead = null; if(src1 == null){ node = src2; } if(src2 == null){ node = src1; } if(src1 == null || src2 == null){ return node; } while(src1 != null && src2 != null){ if(src1.val <= src2.val){ if(node != null){ node.next = src1; node = node.next; }else{ node = src1; newHead = node; } src1 = src1.next; }else{ if(node != null){ node.next = src2; node = node.next; }else{ node = src2; newHead = node; } src2 = src2.next; } node.next= null; } if(src1 != null){ node.next = src1; } if(src2 != null){ node.next = src2; } return newHead; } }