java - 计算数组内的出现次数

标签 java arrays

我已经按照建议回去了,并开始查看几个月前我错误的一些代码,并一直在尝试更新它,以便它会更有效。

我想要的只是我的方法返回一个包含出现次数的新数组。

例如:count({2,4,0,7,4,2,1,0}) 返回 {2,1,2,0,2,0,0,1}

到目前为止,我的方法是这样的,只是为了记录,我想为了观众的缘故,我正在使用的数组是这样的。

18  29  23  35  23  28  36  27  16  21  33  21  18  33  16  6  19  22  9  26  28  16  19  14  18  12  17  28

这是我的计数类(class)

public int[] count(Integer[] nums)
{
    Integer[] numOccur = new Integer[nums.length]; //new array that will be returned with the occurances

    for (int i = 0; i < nums.length; ++i) //goes through the array for nums.length times.
    {
        Integer count = nums[i]; //assigns count to nums[i]
        numOccur[count]++;         //ERROR
        System.out.println(numOccur[i]); //testing to see if i'm printing the right value
    }

    return numOccur;
}

我得到了

at WeatherSrv.count(WeatherSrv.java:94)
    at WeatherDrv.main(WeatherDrv.java:55)
Java Result: 1

我知道问题发生在我对 array[] numOccur 内的新元素进行分配时,这只是因为我的分配吗?我只是想知道我的方向是否正确。

在我之前的版本中,我只使用了 switch 语句,没有数组,所以这有点不同。

编辑1:我应该发布我正在使用它的主要方法!

weather.count(res) 其中 res 是我在类(class)上方发布的数组

/*这是我的第一篇文章 - 如果有人对如何提出更好的问题有任何建议,请不要犹豫,我想要最清晰的、未给出的答案

最佳答案

您绝对可以按照 @Elliott Frisch 的建议让当前的实现正常工作,但您也可以采用不同的路线并使用 HashMap

这是一个使用 HashMap 的可行解决方案,它的另一个好处是不需要迭代可能大量的空索引,因为只有初始数组中存在的数字才会在 HashMap 中具有值。

import java.util.HashMap;

public class CountOccur
{
  public static void main(String[] args)
  {
    Integer[] arr = new Integer[]{2,4,0,7,4,2,1,0};
    HashMap<Integer, Integer> countMap = count(arr);

    for (Integer key : countMap.keySet()) {
      System.out.println(key + " count: " + countMap.get(key));
   }

  }

  public static HashMap<Integer, Integer> count(Integer[] nums)
  { 
      HashMap<Integer, Integer> countMap = new HashMap<Integer, Integer>();

      for (int i = 0; i < nums.length; ++i)
      {
          Integer count = countMap.get(nums[i]); 
          if (count  == null){
            //first occurrence, enter a value of 1 for count
            countMap.put(nums[i], 1);
          }
          else{
            //already in the HashMap, increment the count
            countMap.put(nums[i], count + 1);
          }

      }

      return countMap;
  }
}

输出:

0 count: 2
1 count: 1
2 count: 2
4 count: 2
7 count: 1

为了解决原始方法的缺点,想象一下输入:{1,1000000}。您需要一个大小为 1000001 的数组,为了处理返回的数组,您需要迭代所有 100 万零 1 个索引,除了两个索引外,所有索引都是空的。

关于java - 计算数组内的出现次数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29596332/

相关文章:

Java:多维数组 - 哪个维度在前?

java - JOGL 中 glDrawPixels() 的数据格式

java - 导航 View : Mark menu as dirty

java - 如何修复此异常不匹配错误?

java - 通过注释类创建带有限定符的@MockBean?

c++ - 数组中基于查询的移位元素

javascript - axios 和响应数据集拆分到多个数组

java - 银行计划未按预期运作

java - 为什么陈述设计模式而不是 If-else

php - 将数组作为 url 参数传递