java count = i,计算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.

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.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值