【发布时间】:2015-12-09 03:46:04
【问题描述】:
作为作业的一部分,我必须编写一个方法来打印链表中的重复值以及它们出现的次数。下面是方法printRepeats(),它使用了辅助方法countRepeats(ListNode node)。
问题是我的方法的输出一遍又一遍地打印重复值。例如,在值为1 1 1 2 3 4 5 6 7 6 的列表中,输出为1 (Occurences = 3) 1 (Occurences = 3) 1 (Occurences = 3) 6 (Occurences = 2) 6 (Occurences = 2)。任何重复的值都应该只打印一次。有什么建议?提前致谢!
public class LinkedList
{
private ListNode first;
public void printRepeats()
{
String ans = "";
ListNode temp = first;
while(temp != null)
{
if(countRepeats(temp) > 1 && ans.indexOf((int)temp.getValue()) == -1)
{
ans += temp.getValue();
System.out.print(temp.getValue() + " (Occurences = " + countRepeats(temp) + ") ");
}
temp = temp.getNext();
}
if(ans.length() == 0)
System.out.print("None of the elements repeat.");
}
private int countRepeats(ListNode node)
{
ListNode temp = first;
int count = 0;
while(temp != null)
{
if((int)temp.getValue() == (int)node.getValue())
count++;
temp = temp.getNext();
}
return count;
}
}
【问题讨论】:
-
使用HashMap
,其中key是列表中的数字,value是它的出现次数。 -
你的规格是什么?你有任何运行时限制或者你可以使用其他数据结构来解决这个问题吗?
-
@CRC 不能使用链表以外的数据结构;就运行时限制而言,代码应该尽可能高效,但这不是主要问题。
-
@JBNizet 我在学校的 AP Computer Science AB 学习,我们还没有学习 HashMaps。
-
将刚刚计算并打印的数字存储在另一个LinkedList中,如果它已经在另一个LinkedList中,则跳过它。或者,在计算一个数字之前,检查它是否不在链表中。
标签: java eclipse linked-list repeat counting