gpt4 book ai didi

java - 如何仅打印字符串数组中的重复项一次

转载 作者:行者123 更新时间:2023-11-30 03:17:07 24 4
gpt4 key购买 nike

我有一个索引为 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) 复杂度。稍后我们将讨论更快的内容。

最佳答案

如果您只能使用原始数组,请创建一个名为 uniques 之类的第二个数组,每次遇到新值时,通过向其中添加新值来扩展该数组。当您迭代flowerPack 中的每个索引时,迭代uniques 以查看它是否已包含当前索引的值。如果是这样,则不执行任何操作,否则添加它。最后,您可以打印出uniques的内容。

关于java - 如何仅打印字符串数组中的重复项一次,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32300759/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com