一 题目
Merge two sorted linked lists and return it as a new list. The new list should be made by splicing together the nodes of the first two lists.
Example:
Input: 1->2->4, 1->3->4 Output: 1->1->2->3->4->4
二 分析
求两个有序链表合成一个有序链 表。easy 级别。
2.1 使用list 排序
这是要排序。我先想到把了l1,l2放到一个list, 排序,再遍历list返回结果。
如果l1的长度为m,l2的长度为n, 遍历两遍。则时间复杂度为O(m+n);
//coner case
if(l1 == null && l2== null){
return null;
}
List<Integer> list =new ArrayList();
while(l1!= null){
list.add(l1.val);
l1 = l1.next;
}
while(l2 != null){
list.add(l2.val);
l2= l2.next;
}
Collections.sort(list);
ListNode res= new ListNode(list.get(0));
ListNode pre =res;
for(int i=1;i<list.size();i++){
ListNode node =new ListNode(list.get(i));
pre.next= node;
pre = pre.next;
}
return res;
Runtime: 3 ms, faster than 20.46% of Java online submissions for Merge Two Sorted Lists.
Memory Usage: 38.3 MB, less than 19.53% of Java online submissions forMerge Two Sorted Lists.
使用一次遍历
每次取一个值(较小的),然后往后指向,再有另一个判断,直到取到末位。
我自己调试的时候,边界判断导致的异常是常见的。
另外,为了解决一开始head节点不赋值导致空指针异常,临时用一个值填充了下,最后返回结果再丢掉。
public static ListNode mergeTwoLists(ListNode l1, ListNode l2) {
//coner case:同时为空
if(l1 == null && l2== null){
return null;
}
//临时用一个填充下
ListNode res =new ListNode(l1==null?l2.val:l1.val);
ListNode pre =res;
while(l1!= null && l2 != null){
if(l1.val<=l2.val){
pre.next =new ListNode(l1.val);
if(l1!= null){
l1 = l1.next;
}
pre = pre.next;
}else {
pre.next =new ListNode( l2.val);
if(l2!= null){
l2 = l2.next;
}
pre = pre.next;
}
}
while(l1 != null){
pre.next =new ListNode(l1.val);
l1 = l1.next;
pre = pre.next;
}
while(l2 != null){
pre.next =new ListNode(l2.val);
l2 = l2.next;
pre = pre.next;
}
return res.next;
}
Runtime: 0 ms, faster than 100.00% of Java online submissions for Merge Two Sorted Lists.
Memory Usage: 40.8 MB, less than 10.10% of Java online submissions forMerge Two Sorted Lists.
其实看到这个结果也不容易,思路是一致的,就是剪枝尝试了方式,
如果我开始用的((l1!= null && l2 != null&l1.val<=l2.val)||l2== null) 。那么就是1ms。
有时候算法你用对了,可是还是不一定是最快的,只能说优化的不够好。