Created
September 2, 2015 03:56
-
-
Save cxtadment/9c26e6eab6cafa01bd5a to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| /** | |
| * Definition for ListNode. | |
| * public class ListNode { | |
| * int val; | |
| * ListNode next; | |
| * ListNode(int val) { | |
| * this.val = val; | |
| * this.next = null; | |
| * } | |
| * } | |
| */ | |
| public class Solution { | |
| /** | |
| * @param lists: a list of ListNode | |
| * @return: The head of one sorted list. | |
| */ | |
| public ListNode mergeKLists(List<ListNode> lists) { | |
| // write your code here | |
| if (lists.size() == 0) { | |
| return null; | |
| } | |
| ListNode result = mergeHelper(lists, 0, lists.size() - 1); | |
| return result; | |
| } | |
| public ListNode mergeHelper(List<ListNode> lists, int start, int end) { | |
| if (start == end) { | |
| return lists.get(start); | |
| } | |
| int mid = start + (end - start) / 2; | |
| ListNode left = mergeHelper(lists, start, mid); | |
| ListNode right = mergeHelper(lists, mid + 1, end); | |
| return mergeTwoLists(left, right); | |
| } | |
| public ListNode mergeTwoLists(ListNode list1, ListNode list2) { | |
| ListNode dummy = new ListNode(0); | |
| ListNode curr = dummy; | |
| while (list1 != null && list2 != null) { | |
| if (list1.val <= list2.val) { | |
| curr.next = list1; | |
| curr = curr.next; | |
| list1 = list1.next; | |
| } else { | |
| curr.next = list2; | |
| curr = curr.next; | |
| list2 = list2.next; | |
| } | |
| } | |
| if (list1 != null) { | |
| curr.next = list1; | |
| } else { | |
| curr.next = list2; | |
| } | |
| return dummy.next; | |
| } | |
| } | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment