我的代码即将结束。我应该找到数字在给定数组中出现的次数。 for 循环未按预期工作。
它们包含数组中的数字,我能够提取重复的单个数字。然后我尝试使用 for 循环查找某个数字出现的次数并将其存储到另一个数组中,这将给我计数。
所有内容都声明为d[]
、b[]
、c[]
for (i = 0; i < k; i++) {
for (j = 0; j < l; j++) {
if (d[i] == c[j]) {
b[i]++;
}
}
}
预期的输出应该是,就像如果 if 的条件为真,b[i]
应该增加一个数字出现的次数,但它给了我一个数组,就像它只是传递一样每个 i
通过 if 条件一次。
最佳答案
您可以使用例如哈希表来实现这一点,将数组编号保存为键,将重复次数保存为值。该函数接收一个整数数组,并返回具有重复项的哈希表:
public static Hashtable<Integer, Integer> getRepitedNumbers( Integer[] numbers) {
Hashtable<Integer, Integer> Result = new Hashtable<Integer, Integer>();
for( int i = 0; i < numbers.length; i++) {
if( Result.containsKey( numbers[ i])) {
//If the current number is saved in the hashtable, you need to increment the
//value (repetitions counter for this number)
Result.put( numbers[ i], Result.get( numbers[ i]) + 1);
} else {
//If the current number doesn't exist, is the first occurrence.
Result.put( numbers[ i], 1);
}
}
//At the end you have a hashtable with each number and the number of occurrences
return Result;
}
关于java - 查找数组中某个数字的次数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57886621/