Merge k Sorted Lists
Merge k sorted linked lists and return it as one sorted list. Analyze and describe its complexity.
Time complexity: O(nlgk).
/** * Definition for singly-linked list. * public class ListNode { * int val; * ListNode next; * ListNode(int x) { * val = x; * next = null; * } * } */ public class Solution { public ListNode mergeKLists(ArrayList<listnode> lists) { // Start typing your Java solution below // DO NOT write main() function if (lists.size() == 0) return null; ArrayList<listnode> klist = new ArrayList<listnode>(); for (int i = 0; i < lists.size(); i++) { ListNode node = lists.get(i); if (node != null) { klist.add(node); } } Collections.sort(klist, new Comparator<listnode>() { public int compare(ListNode n1, ListNode n2) { return n1.val - n2.val; } }); ListNode root = null; ListNode node = null; while (!klist.isEmpty()) { if (root == null) { root = klist.get(0); node = root; } else { node.next = klist.get(0); node = node.next; } klist.set(0, klist.get(0).next); if (klist.get(0) == null) { klist.remove(0); } if (klist.isEmpty()) { break; } Collections.sort(klist, new Comparator<listnode>() { public int compare(ListNode n1, ListNode n2) { return n1.val - n2.val; } }); } return root; } }
No comments:
Post a Comment