【问题标题】:Multiple most frequent elements in array数组中多个最频繁的元素
【发布时间】:2020-08-01 05:37:40
【问题描述】:

假设我们有一个整数列表。我想检测并在屏幕上打印最频繁重复的项目。当最常见的元素只有一个时,我知道该怎么做。但是,如果我们有一个包含这些元素的列表:

10, 5, 2, 1, 2, 4, 6, 6, 6, 6, 10, 10, 10 

我想打印一个六和一个十,所以我的意思是我想打印所有最频繁重复的元素,无论有多少..

【问题讨论】:

  • 你想打印多少频繁的元素?
  • 当最常见的元素只有一个时,我知道该怎么做 -- 你能在问题中添加代码吗?

标签: java list


【解决方案1】:

您需要一个地图(又名字典)数据结构来解决这个问题。这是我能想到的最快、最简洁的解决方案。

public static void main(String[] args){
    int[] arr = new int[]{10, 5, 2, 1, 2, 4, 6, 6, 6, 6, 10, 10, 10};
    printMostFrequent(arr);
}
 
private static void printMostFrequent(int[] arr){
    // Key: number in input array
    // Value: amount of times that number appears in the input array
    Map<Integer, Integer> counts = new HashMap<>();

    // The most amount of times the same number appears in the input array. In this example, it's 4.
    int highestFrequency = 0;
    
    // Iterate through input array, populating map.
    for (int num : arr){
        
        // If number doesn't exist in map already, its frequency is 1. Otherwise, add 1 to its current frequency.
        int currFrequency = counts.getOrDefault(num, 0) + 1;
        
        // Update frequency of current number.
        counts.put(num, currFrequency);
        
        // If the current number has the highest frequency so far, store its frequency for later use.
        highestFrequency = Math.max(currFrequency, highestFrequency);
    }

    // Iterate through unique numbers in array (remember, a Map in Java allows no duplicate keys).
    for (int key : counts.keySet()){
        
        // If the current number has the highest frequency, then print it to console.
        if (counts.get(key) == highestFrequency){
            System.out.println(key);
        }
    }
}

输出

6
10

【讨论】:

    【解决方案2】:
    nums = [10, 5, 2, 1, 2, 4, 6, 6, 6, 6, 10, 10, 10]
    
    def most_recurrent_ints(arr):
        log = {}
        for i in arr:
            if i in log:
                log[i] += 1
            else:
                log[i] =  1
        current_max = 0
        for i in log.values():
            if i > current_max:
                current_max = i
        results = []
        for k, v in log.items():
            if v == current_max:
                results.append(k)
        return results
        
    print(most_recurrent_ints(nums))
    

    我不擅长 Java,但这是 Python 解决方案,也许有人可以翻译。如果您需要,我可以在 JS 中完成。

    【讨论】:

      【解决方案3】:

      您是否考虑过使用字典类型的数据结构?我不是 java 人,所以这可能不漂亮,但它可以满足您的需求:

          final int[] array = new int[]{ 10, 5, 2, 1, 2, 4, 6, 6, 6, 6, 10, 10, 10 };
      
          Map<Integer, Integer> dictionary = new HashMap<Integer,Integer>(); 
          
          for(int i = 0; i < array.length; ++i){
              int val = array[i];
              if(dictionary.containsKey(val)){
                  dictionary.put(val, dictionary.get(val) + 1);
              }else{
                  dictionary.put(val, 1);
              }
          }
      
          for(Map.Entry<Integer,Integer> entry : dictionary.entrySet()){
              System.out.println(entry.getKey() + ": " + entry.getValue());
          }
      

      这将输出:

      1: 1
      2: 2
      4: 1
      5: 1
      6: 4
      10: 4
      

      【讨论】:

        【解决方案4】:
        public static void main(String[] args) {
            MostFrequent(new Integer[] {10, 5, 2, 1, 2, 4, 6, 6, 6, 6, 10, 10, 10});
        }
        
        static void MostFrequent(Integer[] arr) {
            Map<Integer, Integer> count = new HashMap<Integer, Integer>();
            
            for (Integer element : arr) {
                if (!count.containsKey(element)) {
                    count.put(element,0);
                }
                count.put(element, count.get(element) + 1);
            }
        
            Map.Entry<Integer, Integer> maxEntry = null;
            ArrayList<Integer> list = new ArrayList<Integer>();
        
            for (Map.Entry<Integer, Integer> entry : count.entrySet()) {
                if (maxEntry == null || entry.getValue() > maxEntry.getValue()) {
                    list.clear();
                    list.add(entry.getKey());
                    maxEntry = entry;
                }
                else if (entry.getValue() == maxEntry.getValue()) {
                    list.add(entry.getKey());
                }
            }
        
            for (Integer item: list) {
                System.out.println(item); 
            }       
        }
        

        输出:

        6
        10
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2021-01-13
          • 2011-10-06
          • 2020-03-22
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多