标签:ListNode 23 list lists 链表 l1 升序 return null
You are given an array of k
linked-lists lists
, each linked-list is sorted in ascending order.
Merge all the linked-lists into one sorted linked-list and return it.
Input: lists = [[1,4,5],[1,3,4],[2,6]]
Output: [1,1,2,3,4,4,5,6]
Explanation: The linked-lists are:
[
1->4->5,
1->3->4,
2->6
]
merging them into one sorted list:
1->1->2->3->4->4->5->6
方法一:顺序合并
类似于两个list合并
每次取一个list,依次顺序合并
public ListNode mergeKLists(ListNode[] lists) { if (lists.length == 0) return null; ListNode ans = lists[0]; for (int i = 1; i < lists.length; i++) ans = getMergeList( ans, lists[i]); return ans; } public ListNode getMergeList(ListNode l1,ListNode l2){ ListNode dumpy = new ListNode(0); ListNode cur = dumpy; while (l1 != null && l2 != null){ cur.next = l1.val <= l2.val ? l1 : l2; if (l1.val <= l2.val ) l1 = l1.next; else l2 = l2.next; cur = cur.next; } if( l1 != null) cur.next = l1; if (l2 != null) cur.next = l2; return dumpy.next; }
方法二:分治合并
将list分成两组,然后再合并。递归进行
public ListNode mergeKLists(ListNode[] lists) { return merge(lists, 0, lists.length - 1); } public ListNode merge(ListNode[] lists, int l,int r){ if( l == r) return lists[l]; if(l > r) return null; int mid = (l + r) / 2; return mergeList(merge(lists, l ,mid ),merge(lists,mid + 1, r)); } public ListNode mergeList(ListNode l1, ListNode l2){ ListNode dumpy = new ListNode(0); ListNode cur = dumpy; while (l1 != null && l2 != null){ cur.next = l1.val <= l2.val ? l1 : l2; if (l1.val <= l2.val ) l1 = l1.next; else l2 = l2.next; cur = cur.next; } if( l1 != null) cur.next = l1; if (l2 != null) cur.next = l2; return dumpy.next; }
参考链接:
https://leetcode.com/problems/merge-k-sorted-lists/
https://leetcode-cn.com/problems/merge-k-sorted-lists/
标签:ListNode,23,list,lists,链表,l1,升序,return,null 来源: https://www.cnblogs.com/diameter/p/14098493.html
本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享; 2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关; 3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关; 4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除; 5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。