【发布时间】:2015-01-27 10:16:33
【问题描述】:
我正在研究链表,问题是 - 编写一个函数来打印给定链表的中间项(假设 LL 具有奇数个节点)。
方法 1 - 遍历 LL 并使用计数器计算节点数。添加 1(使其成为偶数)并将计数器除以 2(忽略数学差异)。再次遍历 LL,但这次只到达反项并返回。
void GetMiddleTermMethod1(){
//Count the number of nodes
int counter = 0;
Node n = FirstNode;
while (n.next != null){
counter = counter + 1;
n = n.next;
}
counter=counter+1/2;
//now counter is equal to the half of the number of nodes
//now a loop to return the nth term of a LL
Node temp = FirstNode;
for(int i=2; i<=counter; i++){
temp = temp.next;
}
System.out.println(temp.data);
}
方法 2 - 初始化 2 个对节点的引用。一个一次遍历2个节点,另一个只遍历1个。当快速引用到达null(LL结束)时,慢速引用会到达中间并返回。
void GetMiddleTermMethod2(){
Node n = FirstNode;
Node mid = FirstNode;
while(n.next != null){
n = n.next.next;
mid = mid.next;
}
System.out.println(mid.next.data);
}
我有 3 个问题 -
Q1 - 如果我在求职面试中被问到这个问题,我如何知道哪种算法更有效?我的意思是这两个函数都遍历 LL 一次半(第二个函数在一个循环中而不是 2 次,但它仍然遍历 LL 一次半)...
Q2 - 由于两种算法都有 O(n) 的大 O,哪些参数将决定哪个更有效?
Q3 - 计算此类算法效率的一般方法是什么?如果您能将我链接到合适的教程,我将不胜感激...
谢谢
【问题讨论】:
-
我推荐 Thomas H. Cormen 的《算法导论》一书
-
我在代码中看到了一些问题——比如在你的第二种方法中,如果列表中有奇数个项目(例如 3 个)或 1 个项目,你就会遇到问题。为什么不对各种类型的输入运行它,看看结果如何?当 2 种算法具有相同的渐近复杂度时,您通常需要查看其他特征。
标签: java performance algorithm linked-list big-o