计算数组中整数的出现次数

Counting occurrences of integers in an array

我正在编写一个程序来计算输入到数组中的整数的出现次数,例如,如果您输入 1 1 1 1 2 1 3 5 2 3,该程序将打印出不同的数字及其出现次数,像这样:

1 出现 5 次, 2 出现 2 次, 3出现2次, 5 出现 1 次

快完成了,除了一个我想不通的问题:

import java.util.Scanner;
import java.util.Arrays;
public class CountOccurrences
{
   public static void main (String [] args)
   { 

    Scanner scan = new Scanner (System.in);

    final int MAX_NUM = 10;  

    final int MAX_VALUE = 100;

    int [] numList;

    int num;

    int numCount;

    int [] occurrences; 

    int count[];

    String end;

    numList = new int [MAX_NUM];

    occurrences = new int [MAX_NUM];

    count = new int [MAX_NUM];

 do
  {
     System.out.print ("Enter 10 integers between 1 and 100: ");

     for (num = 0; num < MAX_NUM; num++)
     {
        numList[num] = scan.nextInt();
     }

     Arrays.sort(numList);

     count = occurrences (numList); 

     System.out.println();   

     for (num = 0; num < MAX_NUM; num++)
     {
        if (num == 0)
        {
           if (count[num] <= 1)
              System.out.println (numList[num] + " occurs " + count[num] + " time");

           if (count[num] > 1)
              System.out.println (numList[num] + " occurs " + count[num] + " times");
        } 

        if (num > 0 && numList[num] != numList[num - 1])
        {
           if (count[num] <= 1)
              System.out.println (numList[num] + " occurs " + count[num] + " time");

           if (count[num] > 1)
              System.out.println (numList[num] + " occurs " + count[num] + " times");
        }   
     }          

     System.out.print ("\nContinue? <y/n> ");
     end = scan.next(); 

  } while (!end.equalsIgnoreCase("n"));
}


 public static int [] occurrences (int [] list)
 {
      final int MAX_VALUE = 100;

      int num;

      int [] countNum = new int [MAX_VALUE];

      int [] counts = new int [MAX_VALUE];

      for (num = 0; num < list.length; num++)
  {
     counts[num] = countNum[list[num]] += 1;
  }

  return counts;
 } 
}

我遇到的问题是,无论 'num' 的当前值是多少,'count' 只打印出 1,问题不在计算出现次数的方法中,因为当您在变量位置输入数字时,值会发生变化。

有什么方法可以改变它以便正确打印出出现的事件,或者我应该尝试其他方法吗? 解决方案越简单越好,因为我还没有超越一维数组。

感谢您的帮助!

您可以首先初始化一个介于 MIN 和 MAX 之间的值数组。然后您可以在该值出现时添加到数组的每个元素1。像,

Scanner scan = new Scanner(System.in);
final int MAX_NUM = 10;
final int MAX_VALUE = 100;
final int MIN_VALUE = 1;
final int SIZE = MAX_VALUE - MIN_VALUE;
int[] numList = new int[SIZE];
System.out.printf("Enter %d integers between %d and %d:%n", 
        MAX_NUM, MIN_VALUE, MAX_VALUE);
for (int i = 0; i < MAX_NUM; i++) {
  System.out.printf("Please enter number %d: ", i + 1);
  System.out.flush();
  if (!scan.hasNextInt()) {
    System.out.printf("%s is not an int%n", scan.nextLine());
    i--;
    continue;
  }
  int v = scan.nextInt();
  if (v < MIN_VALUE || v > MAX_VALUE) {
    System.out.printf("%d is not between %d and %d%n", 
            v, MIN_VALUE, MAX_VALUE);
    continue;
  }
  numList[v - MIN_VALUE]++;
}
boolean first = true;
for (int i = 0; i < SIZE; i++) {
  if (numList[i] > 0) {
    if (!first) {
      System.out.print(", ");
    } else {
      first = false;
    }
    if (numList[i] > 1) {
      System.out.printf("%d occurs %d times", 
              i + MIN_VALUE, numList[i]);
    } else {
      System.out.printf("%d occurs once", i + MIN_VALUE);
    }
  }
}
System.out.println();

1另见 radix sort counting sort

试试 HashMap。对于这种类型的问题,哈希是非常有效和快速的。

我写了这个函数,它接受数组和 return 一个 HashMap,其键是数字,值是该数字的出现。

public static HashMap<Integer, Integer> getRepetitions(int[] testCases) {    
    HashMap<Integer, Integer> numberAppearance = new HashMap<Integer, Integer>();

    for(int n: testCases) {
        if(numberAppearance.containsKey(n)) {
            int counter = numberAppearance.get(n);
            counter = counter+1;
            numberAppearance.put(n, counter);
        } else {
            numberAppearance.put(n, 1);
        }
    }
    return numberAppearance;
}

现在遍历 hashmap 并像这样打印数字的出现:

HashMap<Integer, Integer> table = getRepetitions(testCases);

for (int key: table.keySet()) {
        System.out.println(key + " occur " + table.get(key) + " times");
}

输出:

我认为如果您使用这种方法,您可以大大简化您的代码。您仍然需要修改以包含 MAX_NUMMAX_VALUE.

public static void main(String[] args) {

    Integer[] array = {1,2,0,3,4,5,6,6,7,8};
    Stack stack = new Stack();

    Arrays.sort(array, Collections.reverseOrder());

    for(int i : array){
        stack.push(i);
    }

    int currentNumber = Integer.parseInt(stack.pop().toString()) , count = 1;

    try {
        while (stack.size() >= 0) {
            if (currentNumber != Integer.parseInt(stack.peek().toString())) {
                System.out.printf("%d occurs %d times, ", currentNumber, count);
                currentNumber = Integer.parseInt(stack.pop().toString());
                count = 1;
            } else {
                currentNumber = Integer.parseInt(stack.pop().toString());
                count++;
            }
        }
    } catch (EmptyStackException e) {
         System.out.printf("%d occurs %d times.", currentNumber, count);
    }
}

我会使用 Bag,这是一个计算某个项目在集合中出现次数的集合。 Apache Commons 有它的一个实现。这是他们的 interface, and here's a sorted tree implementation.

你会这样做:

Bag<Integer> bag = new TreeBag<Integer>();
for (int i = 0; i < numList.length; i++) {
    bag.add(numList[i]);
}
for (int uniqueNumber: bag.uniqueSet()) {
    System.out.println("Number " + uniqueNumber + " counted " + bag.getCount(uniqueNumber) + " times");
}

上面的示例从您的 numList 数组中获取元素并将它们添加到 Bag 中以生成计数,但按惯例您甚至不需要数组。只需将元素直接添加到 Bag 即可。类似于:

// Make your bag.
Bag<Integer> bag = new TreeBag<Integer>();

...

// Populate your bag.
for (num = 0; num < MAX_NUM; num++) {
    bag.add(scan.nextInt());
}

...

// Print the counts for each unique item in your bag.
for (int uniqueNumber: bag.uniqueSet()) {
    System.out.println("Number " + uniqueNumber + " counted " + bag.getCount(uniqueNumber) + " times");
}

我要说的是,我花了一段时间才弄清楚countcountNum这两个变量代表什么,也许需要一些评论。但是最后我发现了错误。

假设输入十个数字是:5, 6, 7, 8, 5, 6, 7, 8, 5, 6

排序后,numList为:5, 5, 5, 6, 6, 6, 7, 7, 8, 8

occurrences()返回的数组count应该是:[1, 2, 3, 1, 2, 3, 1, 2, 1, 2]

实际上这个结果数组中唯一有用的数字是:

count[2]: 3     count number for numList[2]: 5
count[5]: 3     count number for numList[5]: 6
count[7]: 2     count number for numList[7]: 7
count[9]: 2     count number for numList[9]: 8

其他数字,比如3之前的前两个数字1, 2,只是用来递增计算总和的,对吧?所以,你的循环逻辑应该改变如下:

  1. 删除第一个if代码块:

    if (num == 0)
    {
       if (count[num] <= 1)
          System.out.println (numList[num] + " occurs " + count[num] + " time");
    
       if (count[num] > 1)
          System.out.println (numList[num] + " occurs " + count[num] + " times");
    } 
    
  2. 将第二个if条件改为:

    if ((num + 1) == MAX_NUM || numList[num] != numList[num + 1]) {
        ......
    }
    

在此之后,您的代码应该可以正常运行。

顺便说一句,你真的不需要那么复杂。试试 HashMap :)