Merge k Sorted Lists--lintcode
2017-08-25 22:37
176 查看
Description
Merge k sorted linked lists and return it as one sorted list.Analyze and describe its complexity.
Example
Given lists:
[
2->4->null,
null,
-1->null
],
return -1->2->4->null.
看到这个题目,脑子里 想到的是 for循环 遍历比较。没有想到基础排序–归并排序。这个题目考的好像就是归并排序。先亮for循环代码。
这个我是盗别人的代码。我写的真的惨不忍睹。正好可以学习学习别人的代码为什么这么简洁。
利用归并排序的代码:
这个也是盗别人的代码。网址:http://blog.csdn.net/linhuanmars/article/details/19899259
这篇博客有两种写法。讲的也挺仔细的。佩服他,太强悍了,向着他前进
Merge k sorted linked lists and return it as one sorted list.Analyze and describe its complexity.
Example
Given lists:
[
2->4->null,
null,
-1->null
],
return -1->2->4->null.
看到这个题目,脑子里 想到的是 for循环 遍历比较。没有想到基础排序–归并排序。这个题目考的好像就是归并排序。先亮for循环代码。
public ListNode mergeKLists(List<ListNode> lists) { if(lists==null||lists.size()==0) { return null; } ListNode head = lists.get(0); for(int i=1;i<lists.size();i++) { head = mergeTwoLists(head, lists.get(i)); } return head; } ListNode mergeTwoLists(ListNode list1, ListNode list2) { ListNode head = new ListNode(-1); ListNode current = head; while(list1!=null&&list2!=null) { if(list1.val<list2.val) { current.next = list1; list1 = list1.next; } else { current.next = list2; list2 = list2.next; } current = current.next; } if(list1!=null) { current.next = list1; } else { current.next = list2; } return head.next; }
这个我是盗别人的代码。我写的真的惨不忍睹。正好可以学习学习别人的代码为什么这么简洁。
利用归并排序的代码:
public ListNode mergeKLists(ArrayList<ListNode> lists) { if(lists==null || lists.size()==0) return null; return helper(lists,0,lists.size()-1); } private ListNode helper(ArrayList<ListNode> lists, int l, int r) { if(l<r) { int m = (l+r)/2; return merge(helper(lists,l,m),helper(lists,m+1,r)); } return lists.get(l); } private ListNode merge(ListNode l1, ListNode l2) { ListNode dummy = new ListNode(0); dummy.next = l1; ListNode cur = dummy; while(l1!=null && l2!=null) { if(l1.val<l2.val) { l1 = l1.next; } else { ListNode next = l2.next; cur.next = l2; l2.next = l1; l2 = next; } cur = cur.next; } if(l2!=null) cur.next = l2; return dummy.next; }
这个也是盗别人的代码。网址:http://blog.csdn.net/linhuanmars/article/details/19899259
这篇博客有两种写法。讲的也挺仔细的。佩服他,太强悍了,向着他前进
相关文章推荐
- [Lintcode]Merge k Sorted Lists
- LintCode 165. Merge Two Sorted Lists
- [LintCode] Merge k Sorted Lists
- lintcode:Merge k Sorted Lists
- lintcode 容易题 :Merge Two Sorted Lists合并两个排序链表
- [LintCode] Merge Two Sorted Lists 混合插入有序链表
- lintcode-medium-Merge k Sorted Lists
- [Lintcode]Merge Two Sorted Lists
- [LintCode] Merge Two Sorted Lists
- 165. 合并两个排序链表(merge-two-sorted-lists)(c++)----lintcode面试题之链表
- 【LeetCode】-Merge Two Sorted Lists
- leetcode--21. Merge Two Sorted Lists
- Merge Two Sorted Lists
- LeetCode: Merge k Sorted Lists
- leetcode - Merge Two Sorted Lists
- Leetcode 21. Merge Two Sorted Lists
- 【Leetcode】Merge K Sorted Lists (Sorting)
- LeetCode Merge Two Sorted Lists
- Leetcode Merge k Sorted Lists
- LeetCode: Merge Two Sorted Lists