计算Java中数组中的重复次数 [英] Count repetitions in array in java
问题描述
我知道有人问过类似的问题,并且我已经进行了研究许多网站.我尝试使用一些答案,但是我的代码是仍然无法正常工作.
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.
我正在完成以前的任务,以帮助我积累知识Java.请原谅我的代码中的任何错误,我仍在学习Java.
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.
这是我的问题:
执行一个方法计数,给定一个整数元素数组,该方法计数返回另一个数组,该数组包含输入数组中每个整数{0,...,r}的出现次数,其中r是一个整数,表示高位您需要计算的整数的边界.
Implement a method count which, given an array of integer elements, returns another array containing the number of occurrences of each integer {0, ..., r} in the input array, where r is an integer to show the upper boundary of the integers that you need to count.
返回的计数数组的大小为r + 1,其中每个索引i处的元素都对应于出现整数i的次数(其中i在{0,...,r}中).
The returned array of counts will be of size r + 1, where the element at each index i corresponds to the number of occurrences of integer i (with i in {0, ..., r}).
输入数组中从0到r的整数范围之外的元素都可以忽略.
Elements in the input array outside of the integer range from 0 to r can be ignored.
例如,假设输入[0、8、1、3、1、3、10、3]且r为4,则输出应为[1、2、0、3、0].
For example, given the input [0, 8, 1, 3, 1, 3, 10, 3] with r is 4, the output should be [1, 2, 0, 3, 0].
如果输入数组为null或长度为0,则将返回null.
If the input array is null or of length 0, this will return null.
空间要求:方法计数应仅对count数组使用额外的空间.
Space requirements: Method count should only use additional space for the count array.
时间要求:计数应通过输入数组一次计算.
Time requirements: The counts should be calculated in a single pass through the input array.
这是我到目前为止所做的事情,它不符合要求,因此我需要帮助才能找到正确的解决方案:
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;
}
推荐答案
您真的很亲密,但似乎有些错误.
You are really close, but seems maybe a small bit is wrong.
int[] count = new int[r + 1];
for (int i = 0; i < arr.length; i++) {
if( arr[i] <= r) {
count[arr[i]]++;
}
}
我认为上面的方法会起作用,如果您考虑一下,只要该索引在{0 ... r}之内,则arr的每个元素都对应于一个计数索引,因此我们检查该值是否在该索引之内范围,然后我们在count内的那个索引处增加整数.
I think the above will work, if you think about it, each element of arr corresponds to an index in count as long as that index is within {0...r}, so we check that the value is within that range, then we increment the integer at that index within count.
这篇关于计算Java中数组中的重复次数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!