【发布时间】:2015-08-31 07:02:16
【问题描述】:
我有一个索引为 25 的字符串数组。我输入了 25 个元素,我试图显示它们,但是,我只希望元素列出一次,然后是出现次数。到目前为止,出现的次数是正确的,但数组的每次迭代仍然打印多次。我正在使用蛮力方法,因为我不能使用 ArrayList、Map 等。有没有人可以给我提示只打印一次元素的逻辑?方法如下:
private void displayFlowers(String flowerPack[]) {
// TODO: Display only the unique flowers along with a count of any duplicates
/*
* For example it should say
* Roses - 7
* Daffodils - 3
* Violets - 5
*/
for(int i = 0; i < flowerPack.length; i++) {
int count = 0;
for(int j = 0; j < flowerPack.length; j++) {
if(flowerPack[i].equals(flowerPack[j]))
{
count++;
}
}
System.out.println(flowerPack[i] + " - " + count);
}
这里是输出,看看我在说什么:
rose - 6
daffodil - 2
rose - 6
daisy - 3
tulip - 2
wildflower - 3
lily - 3
lily - 3
daisy - 3
rose - 6
wildflower - 3
rose - 6
lilac - 1
daffodil - 2
rose - 6
lily - 3
tulip - 2
wildflower - 3
daisy - 3
rose - 6
carnation - 1
orchid - 1
sunflower - 3
sunflower - 3
sunflower - 3
1: Add an item to the pack.
2: Remove an item from the pack.
3: Sort the contents of the pack.
4: Search for a flower.
5: Display the flowers in the pack.
0: Exit the flower pack interface.
是的,我输入了rose 6 次,但我只希望它显示为:
rose - 6
daffodil -2
daisy - 3
tulip - 2
etc
etc
我知道蛮力在实际生产中表现不佳,但我们正在学习如何手动强制输出,即使它是 O(n^2) 复杂度。稍后我们将进入更快的内容。
【问题讨论】:
-
为什么不能使用
ArrayList、Map等?Set听起来正是您想要的。 -
两个提示:(1)您应该在外循环的索引 + 1 处开始内循环。(2)使用另一个(布尔)数组来跟踪您计算过的花朵。
-
对不起,我没有提到 Set。我们还没有走到那一步,所以我们仅限于我们目前的知识范围。
-
如果有人要否决他的问题,也许他们可以有礼貌地解释为什么这样做?
-
@luane:我在下面的回答中阐述了这个想法,但不鼓励或提及在当前索引之外的索引处启动计数循环的优化,因为这不是实现正确的必要条件输出并可能会混淆 OP。
标签: java arrays string duplicates