如何获取数组中出现次数最少的五个元素

3
如果我有以下字符串数组。
String inStrings[] = {"A", "B", "C", "D", "E", "F", "G", "H", "A", "B", "C", "D", "E", "A", "B", "C", "D", "A", "B"};

这个数组随后传递给一个方法,我不确定如何继续。

    static void getColdSearch(String[] inArray){



}

这个方法的作用是获取数组中重复最少的字符串,然后在输出中打印出五个重复最少的字符串。重复的字符串不必相邻,如果少于五个字符串,则所有字符串都应包含在输出中。例如,如果数组列表看起来像上面的示例,则输出应该类似于此。

F //(Occurs once)
G //(Occurs once)
H //(Occurs once)
E //(Occurs twice)
D //(if two different elements repeat the same number of times a random one of them should be printed)

我该怎么做?


2
使用 Map,将数组中的字母作为键,值为计数器。然后找到前五个最小值,就可以了。开始吧。 - AntonH
步骤1. 计算每个元素的数量。步骤2. 从最少到最频繁计算计数。步骤3. 返回在步骤2中构建的排序列表的前几个元素。 - DwB
2
你应该先尝试一些方法。如果不行,再寻求帮助。不要让我们为你解决问题。 - lucasvw
1
这听起来像是一项作业任务 - 你已经尝试了什么,问题具体在哪里? - goerlibe
这是一个任务,我不知道从哪里开始,所以感谢这个,我会尝试使用HashMap,谢谢! - VICWICIV
3个回答

4

尝试使用Java 8功能

import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;

public class GroupingDemo {

    public static void getColdSearch(String[] inArray) {
        Map<String, Long> groupingByLetter = Arrays.stream(inArray)
            .collect(Collectors.groupingBy(Function.identity(), Collectors.counting()));

        List<String> result = groupingByLetter.entrySet().stream()
            .sorted(Map.Entry.comparingByValue())
            .limit(5)
            .map(Map.Entry::getKey)
            .collect(Collectors.toList());

        System.out.println(result);
    }

    public static void main(String[] args) {
        String inStrings[] = {"A", "B", "C", "D", "E", "F", "G", "H", "A", "B", "C", "D", "E", "A", "B", "C", "D", "A", "B"};
        getColdSearch(inStrings);
    }
}

1
使用最大堆(优先队列)和哈希映射。
创建一个类。
         Class WordCount
          {
             String word;
             int count;
           }  
           PriorityQueue<WordCount>queue // queue to save minimum repeated words
           HashMap<String,Integer>map // save data for each word   

循环遍历数组

对于前5个唯一的单词,保存在队列中

检查映射中的数据。如果单词存在,则更新计数

检查队列中的顶部元素。如果单词的计数高于当前索引单词,则从队列中删除该单词并添加此单词。 重复此过程直到循环结束。

最后从队列中取出所有元素


1
您可以按照上述步骤使用Java 8。以下是一种解决方案,或许有助于理解如何在Java 7或更早版本中执行相同的操作。此外,我认为了解底层实现原理是很有帮助的。
static void getColdSearch(String[] inArray) {
    Map<String, Integer> counterMap = new HashMap<>();


    // load the array in a Map instance
    for (String in : inArray) {
        if (null != counterMap.putIfAbsent(in, 1) ) {
        counterMap.put(in, counterMap.get(in) + 1);
        }
    }

    // Question: why do we need a priority queue?
    // We could also use sort based on the values. Search 
    // stackoverflow.com for "sorting on map value"
    PriorityQueue<String> heap = new PriorityQueue<>(new Comparator<String>() {

        @Override
        public int compare(String o1, String o2) {
        // sort based on the count.
        return counterMap.get(o1).compareTo(counterMap.get(o2));
        }

    });


    heap.addAll(counterMap.keySet());

    int size = heap.size();
    for (int i = 0; i < size; i++) {
        // you could end it a "5" but I leave that as an exercise.
        String s = heap.poll();
        System.out.println( s + " count: " + counterMap.get(s));
    }
}

1
非常感谢!这真的很有帮助! - VICWICIV

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接