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:
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.
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}).
Elements in the input array outside of the integer range from 0 to r can be ignored.
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].
If the input array is null or of length 0, this will return null.
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]]++;
}
}
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.