gpt4 book ai didi

java - 计算唯一元素的数量

转载 作者:太空宇宙 更新时间:2023-11-04 14:08:50 26 4
gpt4 key购买 nike

嗨,所以我应该在排除重复项的数组排序后计算唯一元素的数量,但我得到了错误的输出。

In in = new In(args[0]);
int[] whitelist = in.readAllInts();
Arrays.sort(whitelist);

int count = 0;
for (int i = 0; i < whitelist.length; i++) {
if (whitelist[i] == whitelist[count]) {
count++;
}
}
while (!StdIn.isEmpty()) {
int key = StdIn.readInt();
rank(key, whitelist);
}
System.out.println(count);

}}

预期输出:java InstrumentedBinarySearch tinyW.txt

65

得到:16

我有没有计算过重复的数量或者其他什么?

最佳答案

  int flag = 0;
int count = 0;
for (int i = 0; i < whitelist.length; i++) //Element to be checked for
{
for (int j=0; j< whitelist.length ; j++) //Loop that goes through the whole array
{
if (whitelist[i] == whitelist[j]) //checks if there are duplicates
{
flag++; // count
}
}
if( flag==1) //There should be only 1 instance of the element in the array and that is the element itself
{
System.out.println(whitelist[i]); //displays unique element
count++; // Keeps count
}
}

关于java - 计算唯一元素的数量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28575173/

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