【发布时间】:2017-08-23 02:41:24
【问题描述】:
我在找一些考试练习时在 Leetcode 上遇到了这个问题,我想出了以下解决方案:
public class ListNode {
int val;
ListNode next;
ListNode(int x) { val = x; }
}
public class Solution {
public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
// base case: if any one of the lists are empty then we are done.
if (l1 == null) return l2;
else if (l2 == null) return l1;
ListNode head = new ListNode(-1);
// dummy head node
ListNode prev = head; // pointer to do the modifications on the list
while ((l1 != null) && (l2 != null)) {
// while both lists arent empty
int val;
if (l1.val < l2.val) {
val = l1.val;
l1 = l1.next;
} else {
val = l2.val;
l2 = l2.next;
}
ListNode curr = new ListNode(val); // creates a new node with the chosen value
prev.next = curr; // update pointers
prev = curr;
}
// one of the list is finished. we add the rest onto the list ln
if (l1 == null) prev.next = l2;
else prev.next = l1;
return head.next;
}
}
它似乎通过了所有测试 - 但是我遇到的问题是它比提交的解决方案的 90% 慢。我最近学习了链表,但我仍然对这个概念并不完全满意,这就是为什么在理解上可能存在一些失误,导致这里的代码效率低下。如果有人能解释如何改进我的实现,我将不胜感激。
【问题讨论】:
-
为什么在方法的最后只添加剩余的节点时要创建新节点?看来您不必创建新节点,只需(重新)使用传递的节点应该会给您带来相当多的性能改进,尤其是对于长列表。
-
怎么会有人知道为什么你的代码比其他一些未知的代码要慢,而这些代码是一些未指定问题的解决方案?
-
null列表!= 空列表。检查列表的size()及其空值 -
@pvg 好吧,恐怕这是我能得到的最具体的了。这是原来的问题:leetcode.com/problems/merge-two-sorted-lists
-
你只是设法得到更具体的,也许不是。
标签: java algorithm merge linked-list