我有一个索引为25的String数组。我输入了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.
是的,我输了6次玫瑰,但我只想把它显示为:
rose - 6
daffodil -2
daisy - 3
tulip - 2
etc
etc
我知道暴力在实际生产中表现不佳,但我们正在学习如何手动强制输出,即使它是O(n ^ 2)复杂度。我们稍后会介绍更快的内容。
答案 0 :(得分:3)
如果您只使用原始数组,请创建一个名为uniques
的第二个数组,每次遇到新值时,通过向其添加新值来增大该数组。在迭代flowerPack
中的每个索引时,遍历uniques
以查看它是否已包含当前索引的值。如果是这样,什么也不做,否则添加它。最后,您可以打印出uniques
。
答案 1 :(得分:0)
既然你已经说过你不能使用任何图书馆课程,并且想要坚持你的基本方法,那么你可以做一点改动,只打印一次给定类型的花。它还可以节省一些计算量。基本上,有一个辅助布尔数组,您可以在其中跟踪是否已经打印了包含指数花的数据。
你已经通过评论表达了对boolean
s的一些不确定性。 boolean
只是true
或false
的代表。数组是一种将单个类型的多个值保持在一起的方式,其中一些顺序与值相关联。在我的解决方案中,我们的想法是你有一个第二个数组,其中布尔数组的索引(表示你关心的数组中的哪个项的数值)用于对应于花数组的索引。因此,布尔数组中的0
项对应于String数组中的0
项,1
项对应于1
项,n
项目到n
项目等。
您可以使用此布尔数组来表示您是否在索引n处打印了有关花类型的信息。
注意:已经删除了解决方案的实际代码,以便通过自己搞清楚细节来鼓励学习。祝你好运!
答案 2 :(得分:0)
为了保持代码最不受影响,我会创建一个像这样的新变量:
private static 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
*/
int isChecked[] = new int[flowerPack.length];
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++;
if(i!=j)isChecked[j] = 1;
}
}
if(isChecked[i]==0)
System.out.println(flowerPack[i] + " - " + count);
}
}
使用数组:String []flowers = new String[]{"rose","sunflower","rose","rose","sunflower","daisy","daisy"};
打印:
rose - 3
sunflower - 2
daisy - 2
希望有所帮助!!
答案 3 :(得分:-1)
您希望仅打印每个单词一次,并且在不使用Set
的情况下执行此操作,您可以确保只打印的单词时间,或最后时间,它发生。让我们先假设: