Leet Code 23 Merge k Sorted Lists - 合并K个有序链表 Java
2016-06-08 00:00
375 查看
摘要: Leet Code 23 Merge k Sorted Lists - 合并K个有序链表 Java
问题原始链接 https://leetcode.com/problems/merge-k-sorted-lists
合并K个有序链表,返回合并后的链表。
K个两两分组合并,合并后的链表再两两分组合并,直到合并成一个链表。
问题原始链接 https://leetcode.com/problems/merge-k-sorted-lists
合并K个有序链表,返回合并后的链表。
K个两两分组合并,合并后的链表再两两分组合并,直到合并成一个链表。
[code=language-java]/** * Definition for singly-linked list. * public class ListNode { * int val; * ListNode next; * ListNode(int x) { val = x; } * } */ public class Solution { public static ListNode mergeKLists(ListNode[] lists) { if (lists == null || lists.length == 0) { return null; } if (lists.length == 1) { return lists[0]; } else if (lists.length == 2) { return mergeTwoLists(lists[0], lists[1]); } else { int half = (lists.length & 1) == 0 ? lists.length / 2 : lists.length / 2 + 1; ListNode[] merged = new ListNode[half]; for (int i = 0; i < half; i++) { if (lists.length - 1 - i != i) { merged[i] = mergeTwoLists(lists[i], lists[lists.length - 1 - i]); } else { merged[i] = lists[i]; } } return mergeKLists(merged); } } public static ListNode mergeTwoLists(ListNode l1, ListNode l2) { ListNode dummyHead = new ListNode(0); ListNode p = dummyHead; while (l1 != null && l2 != null) { if (l1.val <= l2.val) { p.next = l1; l1 = l1.next; } else { p.next = l2; l2 = l2.next; } p = p.next; } p.next = l1 != null ? l1 : l2; return dummyHead.next; } }
相关文章推荐
- leetcode 179 Largest Number
- leetcode 24 Swap Nodes in Pairs
- leetcode 2 Add Two Numbers 方法1
- leetcode 2 Add Two Numbers 方法2
- leetcode----Longest Substring Without Repeating Characters
- [LeetCode]47 Permutations II
- [LeetCode]65 Valid Number
- [LeetCode]123 Best Time to Buy and Sell Stock III
- [LeetCode] String Reorder Distance Apart
- [LeetCode] Sliding Window Maximum
- [LeetCode] Find the k-th Smallest Element in the Union of Two Sorted Arrays
- [LeetCode] Determine If Two Rectangles Overlap
- [LeetCode] A Distance Maximizing Problem
- leetcode_linearList
- leetcode_linearList02
- 021-Merge Two Sorted Lists(合并两个排好序的单链表);leetcode
- LeetCode[Day 1] Two Sum 题解
- LeetCode[Day 2] Median of Two Sorted Arrays 题解
- LeetCode[Day 3] Longest Substring Without... 题解
- LeetCode [Day 4] Add Two Numbers 题解