给定一个数组,找出其中出现频率最高的元素。如果有多个元素出现的次数最多,则打印其中任何一个。
例子:
Input : arr[] = {1, 3, 2, 1, 4, 1}
Output : 1
1 appears three times in array which
is maximum frequency.
Input : arr[] = {10, 20, 10, 20, 30, 20, 20}
Output : 20
一个简单的解决方案是运行两个循环。外循环一一选取所有元素。内循环查找所选元素的频率并与迄今为止的最大值进行比较。此解决方案的时间复杂度为 O(n 2 )
更好的解决方案是进行排序。我们首先对数组进行排序,然后线性遍历数组。
C++
// CPP program to find the most frequent element
// in an array.
#include
using namespace std;
int mostFrequent(int arr[], int n)
{
// Sort the array
sort(arr, arr + n);
// find the max frequency using linear traversal
int max_count = 1, res = arr[0], curr_count = 1;
for (int i = 1; i < n; i++) {
if (arr[i] == arr[i - 1])
curr_count++;
else {
if (curr_count > max_count) {
max_count = curr_count;
res = arr[i - 1];
}
curr_count = 1;
}
}
// If last element is most frequent
if (curr_count > max_count)
{
max_count = curr_count;
res = arr[n - 1];
}
return res;
}
// driver program
int main()
{
int arr[] = { 1, 5, 2, 1, 3, 2, 1 };
int n = sizeof(arr) / sizeof(arr[0]);
cout << mostFrequent(arr, n);
return 0;
}
Java
//Java program to find the most frequent element
//in an array
import java.util.*;
class GFG {
static int mostFrequent(int arr[], int n)
{
// Sort the array
Arrays.sort(arr);
// find the max frequency using linear
// traversal
int max_count = 1, res = arr[0];
int curr_count = 1;
for (int i = 1; i < n; i++)
{
if (arr[i] == arr[i - 1])
curr_count++;
else
{
if (curr_count > max_count)
{
max_count = curr_count;
res = arr[i - 1];
}
curr_count = 1;
}
}
// If last element is most frequent
if (curr_count > max_count)
{
max_count = curr_count;
res = arr[n - 1];
}
return res;
}
// Driver program
public static void main (String[] args) {
int arr[] = {1, 5, 2, 1, 3, 2, 1};
int n = arr.length;
System.out.println(mostFrequent(arr,n));
}
}
// This code is contributed by Akash Singh.
Python3
# Python3 program to find the most
# frequent element in an array.
def mostFrequent(arr, n):
# Sort the array
arr.sort()
# find the max frequency using
# linear traversal
max_count = 1; res = arr[0]; curr_count = 1
for i in range(1, n):
if (arr[i] == arr[i - 1]):
curr_count += 1
else :
if (curr_count > max_count):
max_count = curr_count
res = arr[i - 1]
curr_count = 1
# If last element is most frequent
if (curr_count > max_count):
max_count = curr_count
res = arr[n - 1]
return res
# Driver Code
arr = [1, 5, 2, 1, 3, 2, 1]
n = len(arr)
print(mostFrequent(arr, n))
# This code is contributed by Smitha Dinesh Semwal.
C#
// C# program to find the most
// frequent element in an array
using System;
class GFG {
static int mostFrequent(int []arr, int n)
{
// Sort the array
Array.Sort(arr);
// find the max frequency using
// linear traversal
int max_count = 1, res = arr[0];
int curr_count = 1;
for (int i = 1; i < n; i++)
{
if (arr[i] == arr[i - 1])
curr_count++;
else
{
if (curr_count > max_count)
{
max_count = curr_count;
res = arr[i - 1];
}
curr_count = 1;
}
}
// If last element is most frequent
if (curr_count > max_count)
{
max_count = curr_count;
res = arr[n - 1];
}
return res;
}
// Driver code
public static void Main ()
{
int []arr = {1, 5, 2, 1, 3, 2, 1};
int n = arr.Length;
Console.WriteLine(mostFrequent(arr,n));
}
}
// This code is contributed by vt_m.
PHP
$max_count)
{
$max_count = $curr_count;
$res = $arr[$i - 1];
}
$curr_count = 1;
}
}
// If last element
// is most frequent
if ($curr_count > $max_count)
{
$max_count = $curr_count;
$res = $arr[$n - 1];
}
return $res;
}
// Driver Code
{
$arr = array(1, 5, 2, 1, 3, 2, 1);
$n = sizeof($arr) / sizeof($arr[0]);
echo mostFrequent($arr, $n);
return 0;
}
// This code is contributed by nitin mittal
?>
Javascript
C++
// CPP program to find the most frequent element
// in an array.
#include
using namespace std;
int mostFrequent(int arr[], int n)
{
// Insert all elements in hash.
unordered_map hash;
for (int i = 0; i < n; i++)
hash[arr[i]]++;
// find the max frequency
int max_count = 0, res = -1;
for (auto i : hash) {
if (max_count < i.second) {
res = i.first;
max_count = i.second;
}
}
return res;
}
// driver program
int main()
{
int arr[] = { 1, 5, 2, 1, 3, 2, 1 };
int n = sizeof(arr) / sizeof(arr[0]);
cout << mostFrequent(arr, n);
return 0;
}
Java
//Java program to find the most frequent element
//in an array
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;
class GFG {
static int mostFrequent(int arr[], int n)
{
// Insert all elements in hash
Map hp =
new HashMap();
for(int i = 0; i < n; i++)
{
int key = arr[i];
if(hp.containsKey(key))
{
int freq = hp.get(key);
freq++;
hp.put(key, freq);
}
else
{
hp.put(key, 1);
}
}
// find max frequency.
int max_count = 0, res = -1;
for(Entry val : hp.entrySet())
{
if (max_count < val.getValue())
{
res = val.getKey();
max_count = val.getValue();
}
}
return res;
}
// Driver code
public static void main (String[] args) {
int arr[] = {1, 5, 2, 1, 3, 2, 1};
int n = arr.length;
System.out.println(mostFrequent(arr, n));
}
}
// This code is contributed by Akash Singh.
Python3
# Python3 program to find the most
# frequent element in an array.
import math as mt
def mostFrequent(arr, n):
# Insert all elements in Hash.
Hash = dict()
for i in range(n):
if arr[i] in Hash.keys():
Hash[arr[i]] += 1
else:
Hash[arr[i]] = 1
# find the max frequency
max_count = 0
res = -1
for i in Hash:
if (max_count < Hash[i]):
res = i
max_count = Hash[i]
return res
# Driver Code
arr = [ 1, 5, 2, 1, 3, 2, 1]
n = len(arr)
print(mostFrequent(arr, n))
# This code is contributed
# by Mohit kumar 29
C#
// C# program to find the most
// frequent element in an array
using System;
using System.Collections.Generic;
class GFG
{
static int mostFrequent(int []arr,
int n)
{
// Insert all elements in hash
Dictionary hp =
new Dictionary();
for (int i = 0; i < n; i++)
{
int key = arr[i];
if(hp.ContainsKey(key))
{
int freq = hp[key];
freq++;
hp[key] = freq;
}
else
hp.Add(key, 1);
}
// find max frequency.
int min_count = 0, res = -1;
foreach (KeyValuePair pair in hp)
{
if (min_count < pair.Value)
{
res = pair.Key;
min_count = pair.Value;
}
}
return res;
}
// Driver code
static void Main ()
{
int []arr = new int[]{1, 5, 2,
1, 3, 2, 1};
int n = arr.Length;
Console.Write(mostFrequent(arr, n));
}
}
// This code is contributed by
// Manish Shaw(manishshaw1)
Javascript
C++
#include
using namespace std;
int maxFreq(int *arr, int n) {
//using moore's voting algorithm
int res = 0;
int count = 1;
for(int i = 1; i < n; i++) {
if(arr[i] == arr[res]) {
count++;
} else {
count--;
}
if(count == 0) {
res = i;
count = 1;
}
}
return arr[res];
}
int main()
{
int arr[] = {40,50,30,40,50,30,30};
int n = sizeof(arr) / sizeof(arr[0]);
int freq = maxFreq(arr , n);
int count = 0;
for(int i = 0; i < n; i++) {
if(arr[i] == freq) {
count++;
}
}
cout <<"Element " << maxFreq(arr , n) << " occurs " << count << " times" << endl;;
return 0;
//This code is contributed by Ashish Kumar Shakya
}
Javascript
输出
1
时间复杂度:O(n Log n)
辅助空间:O(1)
一个有效的解决方案是使用散列。我们创建一个哈希表并将元素及其频率计数存储为键值对。最后,我们遍历哈希表并打印具有最大值的键。
C++
// CPP program to find the most frequent element
// in an array.
#include
using namespace std;
int mostFrequent(int arr[], int n)
{
// Insert all elements in hash.
unordered_map hash;
for (int i = 0; i < n; i++)
hash[arr[i]]++;
// find the max frequency
int max_count = 0, res = -1;
for (auto i : hash) {
if (max_count < i.second) {
res = i.first;
max_count = i.second;
}
}
return res;
}
// driver program
int main()
{
int arr[] = { 1, 5, 2, 1, 3, 2, 1 };
int n = sizeof(arr) / sizeof(arr[0]);
cout << mostFrequent(arr, n);
return 0;
}
Java
//Java program to find the most frequent element
//in an array
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;
class GFG {
static int mostFrequent(int arr[], int n)
{
// Insert all elements in hash
Map hp =
new HashMap();
for(int i = 0; i < n; i++)
{
int key = arr[i];
if(hp.containsKey(key))
{
int freq = hp.get(key);
freq++;
hp.put(key, freq);
}
else
{
hp.put(key, 1);
}
}
// find max frequency.
int max_count = 0, res = -1;
for(Entry val : hp.entrySet())
{
if (max_count < val.getValue())
{
res = val.getKey();
max_count = val.getValue();
}
}
return res;
}
// Driver code
public static void main (String[] args) {
int arr[] = {1, 5, 2, 1, 3, 2, 1};
int n = arr.length;
System.out.println(mostFrequent(arr, n));
}
}
// This code is contributed by Akash Singh.
蟒蛇3
# Python3 program to find the most
# frequent element in an array.
import math as mt
def mostFrequent(arr, n):
# Insert all elements in Hash.
Hash = dict()
for i in range(n):
if arr[i] in Hash.keys():
Hash[arr[i]] += 1
else:
Hash[arr[i]] = 1
# find the max frequency
max_count = 0
res = -1
for i in Hash:
if (max_count < Hash[i]):
res = i
max_count = Hash[i]
return res
# Driver Code
arr = [ 1, 5, 2, 1, 3, 2, 1]
n = len(arr)
print(mostFrequent(arr, n))
# This code is contributed
# by Mohit kumar 29
C#
// C# program to find the most
// frequent element in an array
using System;
using System.Collections.Generic;
class GFG
{
static int mostFrequent(int []arr,
int n)
{
// Insert all elements in hash
Dictionary hp =
new Dictionary();
for (int i = 0; i < n; i++)
{
int key = arr[i];
if(hp.ContainsKey(key))
{
int freq = hp[key];
freq++;
hp[key] = freq;
}
else
hp.Add(key, 1);
}
// find max frequency.
int min_count = 0, res = -1;
foreach (KeyValuePair pair in hp)
{
if (min_count < pair.Value)
{
res = pair.Key;
min_count = pair.Value;
}
}
return res;
}
// Driver code
static void Main ()
{
int []arr = new int[]{1, 5, 2,
1, 3, 2, 1};
int n = arr.Length;
Console.Write(mostFrequent(arr, n));
}
}
// This code is contributed by
// Manish Shaw(manishshaw1)
Javascript
输出
1
时间复杂度: O(n)
辅助空间: O(n)
这个问题的一个有效解决方案可以是通过摩尔投票算法来解决这个问题。
注意:以上投票算法仅在最大出现元素超过 (SIZEOFARRAY/2) 次时有效;
在这种方法中,我们将通过计算一个数字所拥有的票数来找到最大出现的整数。
C++
#include
using namespace std;
int maxFreq(int *arr, int n) {
//using moore's voting algorithm
int res = 0;
int count = 1;
for(int i = 1; i < n; i++) {
if(arr[i] == arr[res]) {
count++;
} else {
count--;
}
if(count == 0) {
res = i;
count = 1;
}
}
return arr[res];
}
int main()
{
int arr[] = {40,50,30,40,50,30,30};
int n = sizeof(arr) / sizeof(arr[0]);
int freq = maxFreq(arr , n);
int count = 0;
for(int i = 0; i < n; i++) {
if(arr[i] == freq) {
count++;
}
}
cout <<"Element " << maxFreq(arr , n) << " occurs " << count << " times" << endl;;
return 0;
//This code is contributed by Ashish Kumar Shakya
}
Javascript
输出
Element 30 occurs 3 times
时间复杂度:O(n)
空间复杂度:O(1)
如果您希望与专家一起参加现场课程,请参阅DSA 现场工作专业课程和学生竞争性编程现场课程。