合并K个升序链表
给你一个链表数组,每个链表都已经按升序排列。
请你将所有链表合并到一个升序链表中,返回合并后的链表。
示例 1:
1 2 3 4 5 6 7 8 9 10
| 输入:lists = [[1,4,5],[1,3,4],[2,6]] 输出:[1,1,2,3,4,4,5,6] 解释:链表数组如下: [ 1->4->5, 1->3->4, 2->6 ] 将它们合并到一个有序链表中得到。 1->1->2->3->4->4->5->6
|
示例 2:
示例 3:
提示:
- k == lists.length
- 0 <= k <= 10^4
- 0 <= lists[i].length <= 500
- -10^4 <= lists[i][j] <= 10^4
- lists[i] 按 升序 排列
- lists[i].length 的总和不超过 10^4
代码:
第一次提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38
| class Solution { public ListNode mergeKLists(ListNode[] lists) { ListNode head=null; ListNode temp=null; ListNode cur=null; if(lists==null||lists.length==0)return null; while (true) { int index=-1; int flag=0; for(int i=0;i<lists.length;i++) { if(lists[i]==null)continue; if(index==-1)index=i; flag=1; if(lists[i].val<lists[index].val) { index=i; } } if(flag==0)break; temp=lists[index].next; if(head==null) { head=lists[index]; cur=head; } else { cur.next=lists[index]; cur=cur.next; } lists[index].next=null; lists[index]=temp; } return head; }
}
|
第二次提交100% 84%:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35
| class Solution { public ListNode mergeKLists(ListNode[] lists) { return merge(lists, 0, lists.length-1); } public ListNode mergeTwoList(ListNode l1, ListNode l2) { if (l1 == null || l2 == null) { return l1==null?l2:l1; } ListNode dummy = new ListNode(-1); ListNode pre = dummy; while (l1 != null && l2 != null) { if (l1.val < l2.val) { pre.next = l1; l1 = l1.next; } else { pre.next = l2; l2 = l2.next; } pre = pre.next; } pre.next = l1==null?l2:l1; return dummy.next; } public ListNode merge(ListNode[] lists, int left, int right) { if (left > right) { return null; } if (left == right) { return lists[left]; } int mid = (left + right) >> 1; return mergeTwoList(merge(lists, left, mid), merge(lists, mid+1, right)); } }
|