【问题标题】:Counting an Occurrence in an Array (Java)计算数组中的出现次数 (Java)
【发布时间】:2015-06-19 12:34:13
【问题描述】:

我完全被难住了。我休息了几个小时,我似乎无法弄清楚这一点。好难过!

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

要求用户输入 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次。”此打印将以单独的方法完成。

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

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;
}

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

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

【问题讨论】:

  • 你在比较 numbers[i] 和 numbers[i];它永远是真实的并增加计数......
  • 另外,还有一个多余的分号。
  • 您的意思是“计算重复次数”而不是“计算出现次数”吗?您想从getOccurrences() 返回的int 是什么?显示一个示例小数组以及传递给您的方法时期望返回的内容
  • @Z̷͙̗̻͖̣̹͉̫̬̪̖̤͆ͤ̓ͫͭ̀̐͜͞ͅͅαлγo你的名字很烦人:)
  • @Bohemian 要求用户输入 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 次。

标签: java arrays


【解决方案1】:

你需要两个循环:

  1. 你从哪里开始

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

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

【讨论】:

    【解决方案2】:

    你可以找到你的问题的答案here

    我在示例中使用了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);
        }
    }
    

    【讨论】:

      【解决方案3】:

      @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 我稍微调整了您的代码,以便每个元素都不会出现打印。

      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;
              }
      
          }
      

      【讨论】:

        【解决方案4】:

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

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

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

        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;
                }
        }
        

        【讨论】:

          【解决方案5】:
          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////////////////////////

          输入 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 次
          构建成功(总时间:3 分 23 秒)

          【讨论】:

          • 嗨,Brenda,你的代码很好,但是我没有什么要问的,首先count[temp]++ 是做什么的,经过我的努力,我还是不明白? 其次 count[] 怎么会在没有输入内容的情况下获取值? 第三 为什么下一个数组是从1开始而不是从0开始呢?能否请您简要介绍一下,以便我清除我的概念。谢谢:)
          • 嗨,Alok,谢谢。首先,count[temp]++ 在 temp 的索引处加一。这是完美的,因为如果我们有一个用户输入,例如 111,num 数组包含这些值,并且每次我们临时将每个值放入 temp 变量并将其用作我们在 count 数组中的索引。例如,temp = 1 => count[temp]++;或计数[1]++;或计数[1] = 计数[1] + 1;因此,由于 count 数组中的每个元素都包含一个零,因此我们访问其内容并添加一个 1。当我们遍历所有三个 1 时,我们在 count[1] 处得到值 3,因此输入了 3 次。
          • 第二,我想我在第一个问题中回答了这个问题,如果您仍然感到困惑,请告诉我。第三,好的,在第一个 for 循环中,我从 0 开始,因为我确实想访问 num 数组的第一个元素来检索用户输入,在第二个循环中,我不需要从索引零开始,因为 0 决定了我们输入的停止,我们从不只计算数字 1 - 100 的零频率。
          【解决方案6】:

          只需复制并执行它,它将为您提供数组中整数的出现次数。

          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");
              }
            }
          }
          

          【讨论】:

            【解决方案7】:
            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 "); 
            
                        }
                    }
                }
            }
            

            【讨论】:

              【解决方案8】:

              最有效的方法是在迭代数组时创建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);
                     }
                   }
              

              【讨论】:

                【解决方案9】:
                // i use List<Integer> to solve the problem. it's not a concise way
                
                public static List<List<Integer>> occurence(int[] cards) {
                
                  // 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;
                }
                

                【讨论】:

                  【解决方案10】:

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

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

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

                  这将产生以下输出:

                  香蕉=1

                  橙色=1

                  苹果=2

                  【讨论】:

                    【解决方案11】:
                    import java.io.BufferedReader;
                    import java.io.FileNotFoundException;
                    import java.io.FileReader;
                    import java.io.IOException;
                    import java.util.ArrayList;
                    import java.util.HashMap;
                    import java.util.List;
                    import java.util.Map;
                     // This program counts the number of occurrences of error message. It read the data from Excel sheet for the same.
                    public class fileopen {
                        public static void main(String[] args) {
                    
                            String csvFile = "C:\\Users\\2263\\Documents\\My1.csv";
                            BufferedReader br = null;
                            String line = "";
                            String cvsSplitBy = ",";
                            List<String> list = new ArrayList<String>();
                    
                            String[] country = null;
                            Map<String, Integer> hm = new HashMap<String, Integer>();
                            try {
                    
                                br = new BufferedReader(new FileReader(csvFile));
                                while ((line = br.readLine()) != null) {
                    
                                    // use comma as separator
                                    country = line.split(cvsSplitBy);
                    
                                    list.add(country[2]);
                    
                                    System.out.println(country[1]);
                                }
                                for (String i : list) {
                                    Integer j = hm.get(i);
                                    hm.put(i, (j == null) ? 1 : j + 1);
                                }
                                // displaying the occurrence of elements in the arraylist
                                for (Map.Entry<String, Integer> val : hm.entrySet()) {
                                    if(val.getKey().equals("Error Message")){
                                        System.out.println(val.getKey());
                                        continue;
                                    }
                                    System.out.println(val.getKey() + " " + val.getValue());
                                }
                            } catch (FileNotFoundException e) {
                                e.printStackTrace();
                            } catch (IOException e) {
                                e.printStackTrace();
                            } finally {
                                if (br != null) {
                                    try {
                                        br.close();
                                    } catch (IOException e) {
                                        e.printStackTrace();
                                    }
                                }
                            }
                        }
                    }
                    

                    【讨论】:

                    • 请添加一些描述,以便 OP 可以从您的回答中学习并帮助他了解问题所在。
                    【解决方案12】:
                    int [] arr = new int [] {1, 2, 8, 3, 2, 2, 2, 5, 1};  
                    
                    //Array fr will store frequencies of element  
                    int [] fr = new int [arr.length];  
                    int visited = -1;  
                    for(int i = 0; i < arr.length; i++){  
                        int count = 1;  
                        for(int j = i+1; j < arr.length; j++){  
                            if(arr[i] == arr[j]){  
                                count++;  
                                //To avoid counting same element again  
                                fr[j] = visited;  
                            }  
                        }  
                        if(fr[i] != visited)  
                            fr[i] = count;  
                    }
                    

                    【讨论】:

                      【解决方案13】:
                      import java.util.*;
                      
                      public class NumberOfOccurences {
                          public static void main(String[] args) {
                      
                              HashMap<Integer, Integer> results = new HashMap<Integer, Integer>(); // final results
                              LinkedList<Integer> duplicates = new LinkedList<Integer>(); // stores all elements from array except duplicates
                              LinkedList<Integer> numbers = new LinkedList<Integer>(); // stores randomly generated numbers
                      
                              for (int index = 0, size = 1000; index < size; index++) {
                                  numbers.add((int)(Math.random() * size) + 1); // generates random number and add as an element in array
                      
                                  if (!duplicates.contains(numbers.get(index))) {
                                      duplicates.add(numbers.get(index)); // get each element from array except duplicates
                                  }
                              }
                      
                      
                              // still works fine without these below
                              duplicates.sort(Comparator.naturalOrder()); // optional
                              numbers.sort(Comparator.naturalOrder()); // optional
                      
                      
                              // the program that gets the number of occurences of duplicated number
                              for (int temporaryHolder : duplicates) {
                                  int counter = 0;
                      
                                  for (int index = 0; index < numbers.size(); index++) {
                                      if (temporaryHolder == numbers.get(index)) {
                                          counter++;
                                      }
                                  }
                                  results.put(temporaryHolder, counter);
                              }
                              // end of program
                      
                      
                              // printer
                              System.out.println("Elements in Array: *Random Generated Elements*\n");
                              for (int index = 0; index < numbers.size(); index++) {
                                  System.out.print(numbers.get(index) + "  ");
                              }
                              System.out.println("\n\nNo Duplicates: *Elements from Array*\n");
                              for (int index = 0; index < duplicates.size(); index++) {
                                  System.out.print(duplicates.get(index) + "  ");
                              }
                              System.out.println("\n\nNumber of Occurences: *Elements from No Duplicates*\n");
                              for (int index = 0; index < duplicates.size(); index++) {
                                  if (results.get(duplicates.get(index)) >= 2) {
                                      System.out.println("No: " + duplicates.get(index) + " occured " + results.get(duplicates.get(index)) + " times.");
                                  }
                              }
                          }
                      }
                      

                      【讨论】:

                      • 虽然此代码可能会解决问题,including an explanation 关于如何以及为什么解决问题将真正有助于提高您的帖子质量,并可能导致更多的赞成票。请记住,您正在为将来的读者回答问题,而不仅仅是现在提问的人。请edit您的回答添加解释并说明适用的限制和假设。
                      【解决方案14】:

                      这是使用 Java 8 Stream 生成频率图的完整解决方案。注释以解释每个步骤。

                      import java.util.Arrays;
                      import java.util.Map;
                      import java.util.function.Function;
                      import java.util.stream.Collectors;
                      
                      class Scratch {
                          public static void main(String[] args) {
                              int[] numbers = new int[]{1, 1, 2, 3, 3, 4, 5, 6, 7, 8};
                      
                              // Count up the occurrences of each number
                              final Map<Integer, Long> numberToOccurrences = getFrequencyMap(numbers);
                      
                              // Print out the results
                              for (Map.Entry<Integer, Long> entry : numberToOccurrences.entrySet()) {
                                  System.out.println(String.format("%d occurs %d times", entry.getKey(), entry.getValue()));
                              }
                          }
                      
                          public static Map<Integer, Long> getFrequencyMap(int[] numbers) {
                              return Arrays.stream(numbers) // Use Java 8 stream
                                      .boxed() // convert IntStream to Stream<Integer>
                                      .collect(Collectors.groupingBy(
                                              Function.identity(), // Key - the number
                                              Collectors.counting() // Value - occurrences of the number
                                      ));
                          }
                      }
                      

                      运行它会打印输出

                      1 occurs 2 times
                      2 occurs 1 times
                      3 occurs 2 times
                      4 occurs 1 times
                      5 occurs 1 times
                      6 occurs 1 times
                      7 occurs 1 times
                      8 occurs 1 times
                      

                      【讨论】:

                        【解决方案15】:

                        请尝试这 3 种方法可能对您有所帮助

                        方式1:有2个循环

                        public class Main {
                            public static void main(String args[]) {
                                int arr[] = {1,2,2,3,4,1,1,5,5,1};
                                // Arrays.sort(arr);
                                int count = 0;       
                                for(int i=0;i<arr.length;i++){
                                    for(int j=0;j<arr.length;j++){
                                        if(arr[i] == arr[j]){  
                                            if(j<i){
                                                break;
                                            }                   
                                            count++;
                                        }               
                                    } 
                                    if(count > 0){  
                                        System.out.println("occurence of "+arr[i]+"  "+(count));                 
                                        count = 0;
                                    }
                                 }         
                            }
                        }
                        

                        方式 2: 有 1 个循环

                        public class Main {
                            public static void main(String args[]) {
                                int arr[] = {1,2,2,3,4,1,1,5,5,1};
                                // Arrays.sort(arr);
                                int count = 0;  
                                int temp = 0;
                                for(int i=0;i<arr.length;i++){              
                                    if(arr[count] == arr[i]){  
                                         if(i<count){
                                            if(count<arr.length-1)
                                               count++;
                                             i=0;
                                                //  break;
                                          }else{
                                            temp++;  
                                          }
                                    } 
                                                       
                                   if(i == arr.length-1 && temp > 0){
                                        System.out.println("occurence of "+arr[count]+"  "+(temp)+". "+i);                 
                                        temp = 0;   
                                    }
                                          
                                   if(i == arr.length-1 && count<i){
                                       if(count<arr.length-1)
                                          count++;
                                       i=0;                 
                                    }        
                                  }   
                            }
                        }
                        

                        方式3:带switch语句

                        public class Main {
                            public static void main(String args[]) {
                                int arr[] = {1,2,2,3,4,1,1,5,5,1};
                                // Arrays.sort(arr);
                                int count = 0; 
                                int temp = 0;
                                for(int i=0;i<arr.length;i++){ 
                                      switch(0){
                                          case -1:
                                          default:
                                            if(arr[count] == arr[i]){  
                                              if(i<count){
                                                if(count<arr.length-1)
                                                  count++;
                                                 i=0;
                                                 break;
                                            }else{
                                                temp++;  
                                            }
                                          } 
                                      }                  
                                   
                                    if(i == arr.length-1 && temp > 0){
                                        System.out.println("occurence of "+arr[count]+"  "+(temp)+". "+i);                 
                                        temp = 0;   
                                    }
                                          
                                    if(i == arr.length-1 && count<i){
                                        if(count<arr.length-1)
                                          count++;
                                        i=0;                 
                                    }        
                                 }   
                            }
                        }
                        

                        【讨论】:

                          猜你喜欢
                          • 2017-03-24
                          • 1970-01-01
                          • 2017-02-13
                          • 2015-06-18
                          • 1970-01-01
                          • 1970-01-01
                          • 2011-12-27
                          相关资源
                          最近更新 更多