# “数组中多个最常见的元素”

go评论65阅读模式

Multiple most frequent elements in array

# 问题

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

Suppose we have a list of integers. I would like to detect and print on the screen the most frequently repeated item . I know how to do it when the most common element is only one. However, if we have such a list which contains these elements:

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

i want to print a six and a ten so I mean I want to print all the most frequently repeated elements no matter how many there are..

# 答案1

Sure, here's the translated Python code:

``````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))
``````

Please note that the code translation is provided as requested, and no additional content or answers are included.

``````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 &gt; 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))
``````

I'm bad at Java but this is the Python solution, maybe someone can translate. I can do it in JS if you need.

# 答案2

``````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
``````

Have you considered using a dictionary-type data structure? I am not a java person, so this may not be pretty, but it does what you are looking for:

``````    final int[] array = new int[]{ 10, 5, 2, 1, 2, 4, 6, 6, 6, 6, 10, 10, 10 };

Map&lt;Integer, Integer&gt; dictionary = new HashMap&lt;Integer,Integer&gt;();

for(int i = 0; i &lt; 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&lt;Integer,Integer&gt; entry : dictionary.entrySet()){
System.out.println(entry.getKey() + &quot;: &quot; + entry.getValue());
}
``````

This would output:

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

# 答案3

``````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();
maxEntry = entry;
}
else if (entry.getValue() == maxEntry.getValue()) {
}
}

for (Integer item: list) {
System.out.println(item);
}
}
``````

``````6
10
``````

``````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&lt;Integer, Integer&gt; count = new HashMap&lt;Integer, Integer&gt;();

for (Integer element : arr) {
if (!count.containsKey(element)) {
count.put(element,0);
}
count.put(element, count.get(element) + 1);
}

Map.Entry&lt;Integer, Integer&gt; maxEntry = null;
ArrayList&lt;Integer&gt; list = new ArrayList&lt;Integer&gt;();

for (Map.Entry&lt;Integer, Integer&gt; entry : count.entrySet()) {
if (maxEntry == null || entry.getValue() &gt; maxEntry.getValue()) {
list.clear();
maxEntry = entry;
}
else if (entry.getValue() == maxEntry.getValue()) {
}
}

for (Integer item: list) {
System.out.println(item);
}
}
``````

Output:

``````6
10
``````

# 答案4

``````你需要一个地图（也称为字典）数据结构来解决这个问题。这是我能想到的最快最简洁的解决方案。

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){
// 键：输入数组中的数字
// 值：数字在输入数组中出现的次数
Map<Integer, Integer> counts = new HashMap<>();

// 同一个数字在输入数组中出现的最大次数。在这个例子中，它是4。
int highestFrequency = 0;

// 遍历输入数组，填充映射。
for (int num : arr){

// 如果数字在映射中不存在，它的频率是1。否则，在当前频率上加1。
int currFrequency = counts.getOrDefault(num, 0) + 1;

// 更新当前数字的频率。
counts.put(num, currFrequency);

// 如果当前数字的频率是目前为止最高的，存储它的频率以备后用。
highestFrequency = Math.max(currFrequency, highestFrequency);
}

// 遍历数组中的唯一数字（请记住，Java中的Map不允许重复的键）。
for (int key : counts.keySet()){

// 如果当前数字具有最高的频率，则将其打印到控制台。
if (counts.get(key) == highestFrequency){
System.out.println(key);
}
}
}
``````

``````6
10
``````

You would need a map (aka dictionary) data structure to solve this problem. This is the fastest and most concise solution I could come up with.

``````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&lt;Integer, Integer&gt; counts = new HashMap&lt;&gt;();

// The most amount of times the same number appears in the input array. In this example, it&#39;s 4.
int highestFrequency = 0;

// Iterate through input array, populating map.
for (int num : arr){

// If number doesn&#39;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);
}
}
}
``````

Output

``````6
10
``````

• 本文由 发表于 2020年7月31日 10:25:09
• 转载请务必保留本文链接：https://go.coder-hub.com/63184911.html
• java
• list

go 50

go 56

go 52

go 98