Counting repeated elements in an integer array

前端 未结 13 1249
挽巷
挽巷 2020-11-27 08:02

I have an integer array crr_array and I want to count elements, which occur repeatedly. First, I read the size of the array and initialize it with numbers read

相关标签:
13条回答
  • 2020-11-27 08:35

    This kind of problems can be easy solved by dictionaries (HashMap in Java).

      // The solution itself 
      HashMap<Integer, Integer> repetitions = new HashMap<Integer, Integer>();
    
      for (int i = 0; i < crr_array.length; ++i) {
          int item = crr_array[i];
    
          if (repetitions.containsKey(item))
              repetitions.put(item, repetitions.get(item) + 1);
          else
              repetitions.put(item, 1);
      }
    
      // Now let's print the repetitions out
      StringBuilder sb = new StringBuilder();
    
      int overAllCount = 0;
    
      for (Map.Entry<Integer, Integer> e : repetitions.entrySet()) {
          if (e.getValue() > 1) {
              overAllCount += 1;
    
              sb.append("\n");
              sb.append(e.getKey());
              sb.append(": ");
              sb.append(e.getValue());
              sb.append(" times");
          }
      }
    
      if (overAllCount > 0) {
          sb.insert(0, " repeated numbers:");
          sb.insert(0, overAllCount);
          sb.insert(0, "There are ");
      }
    
      System.out.print(sb.toString());
    
    0 讨论(0)
提交回复
热议问题