I know that similar questions have been asked and I have researched many websites. I have tried to use some of the answers but my code is still not working.
I am going through a previous assignment to help build my knowledge of Java. Please forgive any errors in my code, I am still learning Java.
Here is my question:
实现一个方法 count,给定一个整数元素数组,返回另一个数组,其中包含输入数组中每个整数 {0, ..., r} 的出现次数,其中 r 是一个整数,用于显示上限值您需要计算的整数的边界。
返回的计数数组的大小为 r + 1,其中每个索引 i 处的元素对应于整数 i 出现的次数(i 在 {0, ..., r} 中)。
可以忽略输入数组中 0 到 r 整数范围之外的元素。
例如,假设输入 [0, 8, 1, 3, 1, 3, 10, 3],r 为 4,则输出应为 [1, 2, 0, 3, 0]。
如果输入数组为 null 或长度为 0,则返回 null。
空间要求:方法 count 应该只为 count 数组使用额外的空间。
时间要求:应在输入数组的单次传递中计算计数。
Here is what I've done so far, it doesn't meet the requirements so I need help in order to find the right solution:
public static int[] count(int[] arr, int r) {
int[] count = new int[r + 1];
for (int i = 0; i < arr.length; i++) {
for (int j = 0; j < r; j++) {
if (arr[i] == j) {
count[i]++;
}
}
}
return count;
}
最佳答案
您确实很接近,但似乎可能有一点错误。
int[] count = new int[r + 1];
for (int i = 0; i < arr.length; i++) {
if( arr[i] <= r) {
count[arr[i]]++;
}
}
我认为上面的方法是可行的,如果你仔细想想,arr 的每个元素都对应于 count 中的一个索引,只要该索引在 {0...r} 之内,所以我们检查该值是否在该范围内范围,然后我们在 count 内增加该索引处的整数。
关于java - java计算数组中的重复次数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53376667/