java - 查找数组中某个数字的次数

标签 java

我的代码即将结束。我应该找到数字在给定数组中出现的次数。 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/

相关文章:

java - HttpServlet - 如何知道是否使用 SSL 客户端身份验证

java - 在 Java 中使用多维数组的 Foreach

java - HttpGet 添加 header

java - 如何为返回子实体的父实体编写存储库方法?

java - 无法从 META-INF 读取文件

jsp - Java Web 应用程序未编译 JSP

带有 x 和 y 坐标的 Javafx Pane

java - 如何使用 toString 和 getter 和 setter 方法

java - 在 Jlist 单元格中显示多行

java.net.ConnectException : Connection refused