计算数组中的出现次数 (Java)

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/29618205/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-11 08:19:37  来源:igfitidea点击:

Counting an Occurrence in an Array (Java)

javaarrays

提问by FrakkinShip

I am completely stumped. I took a break for a few hours and I can't seem to figure this one out. It's upsetting!

我完全被难住了。我休息了几个小时,我似乎无法弄清楚这一点。令人心烦意乱!

I know that I need to check the current element in the array and see if it appears elsewhere in the array. The idea is to output the following:

我知道我需要检查数组中的当前元素,看看它是否出现在数组的其他地方。想法是输出以下内容:

The user is asked to enter 10 integers and those integers are assigned to an array (hence the "numbers" as a paremeter for the method). Let's say I enter "1, 1, 2, 3, 3, 4, 5, 6, 7, 8." The printed results should be "1 occurs 2 times. 2 occurs 1 time. 3 occurs 2 times. 4 occurs 1 time. 5 occurs 1 time. 6 occurs 1 time. 7 occurs 1 time. 8 occurs 1 time." This printing will be done in a separate method.

要求用户输入 10 个整数,并将这些整数分配给一个数组(因此“数字”作为该方法的参数)。假设我输入了“1, 1, 2, 3, 3, 4, 5, 6, 7, 8”。打印的结果应该是“1出现2次。2出现1次。3出现2次。4出现1次。5出现1次。6出现1次。7出现1次。8出现1次。” 此打印将在单独的方法中完成。

Everything in my code works except for this method that I created to count the occurrences.

除了我创建的用于计算出现次数的方法之外,我的代码中的所有内容都有效。

public static int getOccurrences(int[] numbers)
{
    int count = 0;

    for (int i = 0; i < numbers.length; i++)
    {
        int currentInt = numbers[i];;

        if (currentInt == numbers[i])
        {
            count++;
        }
    }

    return count;
}

I know what the issue is here. I set the current integer element in the array to the variable currentInt. The if statement counts every integer element in the array, hence the output being "[I@2503dbd3 occurs 10 times."

我知道这里有什么问题。我将数组中的当前整数元素设置为变量 currentInt。if 语句计算数组中的每个整数元素,因此输出为“[I@2503dbd3 出现 10 次”。

How do I keep track of the occurrences of each element in the array?

如何跟踪数组中每个元素的出现次数?

回答by Shar1er80

You need two loops:

你需要两个循环:

  1. For where you're starting

  2. A nested loop, to be one index in front of where you're currently at, unless you're at the end.

  1. 对于你开始的地方

  2. 一个嵌套循环,作为你当前所在位置前面的一个索引,除非你在最后。

Is there a number you don't EVERY expect to be in your array? If so, use that value (-1 for example) as a sentinel value to overwrite your occurrences as they are counted. Then as you go through the array again for the next number to check for occurrences, you skip it if it has your sentinel value.

是否有您不希望出现在您的数组中的数字?如果是这样,请使用该值(例如 -1)作为标记值,​​以在计数时覆盖您的出现次数。然后,当您再次遍历数组以检查下一个数字是否出现时,如果它具有您的标记值,则跳过它。

回答by loikkk

You can find the answer of your question here

你可以在这里找到你的问题的答案

I used Arrays.sort()method in my example:

Arrays.sort()在我的例子中使用了方法:

public class MyTest {

    /**
     * @param args
     */
    public static void main(String[] args) {

        int[] a = {1, 9, 8, 8, 7, 6, 5, 4, 3, 3, 2, 1};

        Arrays.sort(a);
        int nbOccurences = 0;

        for (int i = 0, length = a.length - 1; i < length; i++) {
            if (a[i] == a[i + 1]) {
                nbOccurences++;
            }
        }

        System.out.println("Number same occurences : " + nbOccurences);
    }
}

回答by Toni

@NYB You're almost right but you have to output the count value and also start it from zero on each element check.

@NYB 你几乎是对的,但你必须输出计数值,并在每个元素检查时从零开始。

    int count=0,currentInt=0;
    for (int i = 0; i < numbers.length; i++)
    {
    currentInt = numbers[i];
    count=0;

       for (int j = 0; j < numbers.length; j++)
           {
             if (currentInt == numbers[j])
                {
                  count++;
                 }
            }
            System.out.println(count);
      }

@loikkk I tweaked your code a bit for print out of occurrence for each element.

@loikkk 我稍微调整了你的代码,以便为每个元素打印出不出现的情况。

int[] a = { 1, 9, 8, 8, 7, 6, 5, 4, 3, 3, 2, 1 };

    Arrays.sort(a);

    int nbOccurences = 1;

    for (int i = 0, length = a.length; i < length; i++) {
        if (i < length - 1) {
            if (a[i] == a[i + 1]) {
                nbOccurences++;
            }
        } else {
            System.out.println(a[i] + " occurs " + nbOccurences
                    + " time(s)"); //end of array
        }

        if (i < length - 1 && a[i] != a[i + 1]) {
            System.out.println(a[i] + " occurs " + nbOccurences
                    + " time(s)"); //moving to new element in array
            nbOccurences = 1;
        }

    }

回答by Kitoliwa

You need to sort the order of your numbers in the array. You can use a 'sort()'method, which will organize your numbers from smallest to biggest.

您需要对数组中数字的顺序进行排序。您可以使用一种'sort()'方法,该方法将从最小到最大组织您的数字。

You also need two loops, one to compare against the other. Or in my solution's case, I used a 'while statement' and then a 'for loop'.

您还需要两个循环,一个用于与另一个进行比较。或者在我的解决方案的情况下,我使用了“ while 语句”,然后使用了“ for 循环”。

I dunno if my method of solving your problem is what you are looking for. Maybe there is a shorter and/or better way to solve this. This is just the way I thought of it. Good luck!

我不知道我解决您问题的方法是否是您正在寻找的。也许有更短和/或更好的方法来解决这个问题。这只是我的想法。祝你好运!

public static int getOccurrences(int[] numbers){

    Array.sort (numbers); //sorts your array in order (i,e; 2, 9, 4, 8... becomes, 2, 4, 8, 9)

    int count = 0;
    int start = 0; 
    int move = 0;

        while(start < numbers.length){
            for (int j = 0; j < numbers.length; j++){
                int currentInt = numbers[start];;
                if (currentInt == numbers[j])
                {
                    count++;
                    move++;
                }
            }
                if(count == 1){
                    return ("Number : " + numbers[start] + " occurs " + count + " time ");
            }   else {
                    return ("Number : " + numbers[start] + " occurs " + count + " times ");
            }
                count = 0;
                start = start + move;
                move = 0;
        }
}

回答by Brenda Mejia

package countoccurenceofnumbers;

import java.util.Scanner;
public class CountOccurenceOfNumbers {


    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        int [] num = new int[100]; 
        int [] count = new int[100];
        //Declare counter variable i
        //and temp variable that will
        //temporarily hold the value
        //at a certain index of num[] array
        int i,temp = 0;
        System.out.println("Enter the integers between 1 and 100: ");

        //Initialize num[] array with user input
        for(i=0; i < num.length; i++){
            num[i] = input.nextInt();
            //expected input will end when user enters zero
            if(num[i] == 0){
                break;
            }
        }//end of for loop

        //value at a given index of num array 
        //will be stored in temp variable
        //temp variable will act as an index value
        //for count array and keep track of number
        //of occurences of each number
        for(i = 0; i < num.length; i++){
                temp = num[i];
                count[temp]++;
            }//end of for looop

        for(i=1; i < count.length; i++){

            if(count[i] > 0 && count[i] == 1){
             System.out.printf("%d occurs %d time\n",i, count[i]);
             }
            else if(count[i] >=2){
                System.out.printf("%d occurs %d times\n",i, count[i]);
            }


         }//end of for loop

    }//end of main
    }//end of CountOccurrenceOfNumbers

///////////OUTPUT//////////////////////

///////////输出//////////////////////

Enter the integers between 1 and 100:
2 5 6 5 4 3 23 43 2 0
2 occurs 2 times
3 occurs 1 time
4 occurs 1 time
5 occurs 2 times
6 occurs 1 time
23 occurs 1 time
43 occurs 1 time
BUILD SUCCESSFUL (total time: 3 minutes 23 seconds)

输入 1 到 100 之间的整数:
2 5 6 5 4 3 23 43 2 0
2 发生 2 次
3 发生 1 次
4 发生 1 次
5 发生 2 次
6 发生 1 次
23 发生 1 次
43 发生 1 次
BUILD SUCCESSFUL(总时间:3分23秒)

回答by Tejaswa Gupta

Just copy and execute it, it will give you the no of occurrence of integers in array.

只需复制并执行它,它就会告诉你数组中没有出现整数。

public class noOfOccurence{  

public static void main(String[] args){

    int a[] = {1,9,4,5,6,7,5,6,7,3,2,5,7,9,0,4,3,5,1,4,6,0,2,3,1,4,3,8};

    HashSet<Integer> al = new HashSet<Integer>();

   //Store the array in set as set will store unique elemnets
    for(int i=0;i<a.length;i++){
        //int count =0; 
        al.add(a[i]);
    }
    //printing the set
    System.out.println("al "+al);


    for(int set : al){
        int count = 0;
        for(int j=0;j<a.length;j++){

            if(set==a[j]){
                count++;
            }
        }
        System.out.println(set+" occurs "+count+" times");
    }
  }
}

回答by Rock Block

import java.util.Scanner;

public class array2 {
    public static void main (String[]args) {
        Scanner input = new Scanner (System.in);
        int [] number = new int [101];
        int c;

        do {

            System.out.println("Enter the integers from 1-100");
            c = input.nextInt();
            number[c]++;

        }while (c != 0);
        for(int i = 0; i < number.length ; i++) {
            if (number[i] !=0) {
                if (number[i] == 1)
                    System.out.println(i + " occurs " + number[i] + " time");
                else
                    System.out.println(i + " occurs " + number[i] + " times "); 

            }
        }
    }
}

回答by Sidharth Taneja

The most efficient way is to create hashmap to save the occurrence of element while iterating the array. It will do it in 2n time complexity which is best for this problem -

最有效的方法是创建 hashmap 来保存迭代数组时元素的出现。它将以 2n 的时间复杂度完成,这最适合这个问题 -

HashMap<Integer, Integer> hmap = new HashMap<Integer, Integer>();
int count;    
for(int i=0;i<arr.length;i++){
       if(hmap.get(arr[i])==null){
         hmap.put(arr[i],1);
       }else{
         count=hmap.get(arr[i]);
         count++;
         hmap.put(arr[i],count);
       }
     }

回答by Mike Xue

// i use List to solve the problem. it's not a concise way

// 我使用 List 来解决这个问题。这不是一种简洁的方式

public static List> occurence(int[] cards) {

公共静态列表>发生(int []卡){

    // first, we create a ArrayList to store the distinct number and its corresponding count value
    //it takes time
    List<List<Integer>> element = new ArrayList<>();

    int tmp=cards[0],  count=0;
    int total = cards.length;

    for(int i=0; i < total; i++) {

        if(i == total -1) {
            if( cards[i] == tmp) {

                    List<Integer> l = new ArrayList<>();
                    l.add(tmp);
                    l.add(count+1);
                    element.add(l);
                    break;
            }else {
                List<Integer> l = new ArrayList<>();
                l.add(tmp);
                l.add(count);
                element.add(l);

                l = new ArrayList<>();
                l.add(cards[i]);
                l.add(1);
                element.add(l);
                break;
            }

        }

        if(cards[i] == tmp) {
            count++;                
        }else { 
            List<Integer> l = new ArrayList<>();
            l.add(tmp);
            l.add(count);
            element.add(l);

            tmp = cards[i];
            count = 1;  //we already have 1 occurence of cards[i]. i.e. tmp             
        }
    }

    return element;
}

回答by Aashish Pawar

We can use java 8 Stream API to create Frequency Map

我们可以使用 java 8 Stream API 创建频率图

Stream.of("apple", "orange", "banana", "apple") .collect(Collectors.groupingBy(Function.identity(), Collectors.counting())) .entrySet() .forEach(System.out::println);

Stream.of("apple", "orange", "banana", "apple") .collect(Collectors.groupingBy(Function.identity(), Collectors.counting())) .entrySet() .forEach(System.out::println);

The downstream operation is itself a collector (Collectors.counting()) that operates on elements of type String and produces a result of type Long. The result of the collect method call is a Map.

下游操作本身是一个收集器 (Collectors.counting()),它对 String 类型的元素进行操作并产生 Long 类型的结果。collect 方法调用的结果是一个 Map。

This would produce the following output:

这将产生以下输出:

banana=1

香蕉=1

orange=1

橙色=1

apple=2

苹果=2