Solution:
1) Divide and Conquer:
/**
* 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.
*/
private ListNode mergeTwoLists(ListNode list1, ListNode list2) {
if (list1 == null) return list2;
if (list2 == null) return list1;
ListNode rst = null;
ListNode dummy = null;
while(list1 != null && list2 != null) {
int val = 0;
if (list1.val < list2.val) {
val = list1.val;
list1 = list1.next;
} else {
val = list2.val;
list2 = list2.next;
}
if(dummy == null) {
dummy = new ListNode(val);
rst = dummy;
} else {
dummy.next = new ListNode(val);
dummy = dummy.next;
}
}
if (list1 == null) dummy.next = list2;
if (list2 == null) dummy.next = list1;
return rst;
}
public ListNode mergeKLists(List<ListNode> lists) {
// write your code here
if (lists.size() == 0) return null;
if (lists.size() == 1) return lists.get(0);
if (lists.size() == 2) return mergeTwoLists(lists.get(0), lists.get(1));
return mergeTwoLists(
mergeKLists(lists.subList(0, lists.size()/2)),
mergeKLists(lists.subList(lists.size()/2, lists.size()))
);
}
}
Subscribe to:
Post Comments (Atom)
4. Ugly Number
1*2(t2) 2*2 3*2 (t3)1*3 2*3 3*3 (t5)1*5 2*5 3*5 1*2 2*2(t2) 3*2 1*3(t3) 2*3 3*3 (t5)1*5 2*5 3*5 Solution: public int nthUglyNumbe...
-
1*2(t2) 2*2 3*2 (t3)1*3 2*3 3*3 (t5)1*5 2*5 3*5 1*2 2*2(t2) 3*2 1*3(t3) 2*3 3*3 (t5)1*5 2*5 3*5 Solution: public int nthUglyNumbe...
-
Question: Given string A representative a positive integer which has N digits, remove any k digits of the number, the remaining digit...
-
Thinking: binary Tree 和 Stringbuilder 的联合题 对Stringbuilder 和StringTokenizer的使用方法的考验 public String serialize(TreeNode root) { ...
No comments:
Post a Comment