数组中最不频繁元素的Java程序
给定一个数组,找出其中出现频率最低的元素。如果有多个元素出现次数最少,则打印其中任何一个。
例子 :
Input : arr[] = {1, 3, 2, 1, 2, 2, 3, 1}
Output : 3
3 appears minimum number of times in given
array.
Input : arr[] = {10, 20, 30}
Output : 10 or 20 or 30
一个简单的解决方案是运行两个循环。外循环一一挑选所有元素。内部循环找到拾取元素的频率并与迄今为止的最小值进行比较。该解决方案的时间复杂度为 O(n 2 )
更好的解决方案是进行排序。我们首先对数组进行排序,然后线性遍历数组。
Java
// Java program to find the least frequent element
// in an array.
import java.io.*;
import java.util.*;
class GFG {
static int leastFrequent(int arr[], int n)
{
// Sort the array
Arrays.sort(arr);
// find the min frequency using
// linear traversal
int min_count = n+1, res = -1;
int curr_count = 1;
for (int i = 1; i < n; i++) {
if (arr[i] == arr[i - 1])
curr_count++;
else {
if (curr_count < min_count) {
min_count = curr_count;
res = arr[i - 1];
}
curr_count = 1;
}
}
// If last element is least frequent
if (curr_count < min_count)
{
min_count = curr_count;
res = arr[n - 1];
}
return res;
}
// driver program
public static void main(String args[])
{
int arr[] = {1, 3, 2, 1, 2, 2, 3, 1};
int n = arr.length;
System.out.print(leastFrequent(arr, n));
}
}
/*This code is contributed by Nikita Tiwari.*/
Java
//Java program to find the least frequent element
//in an array
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;
class GFG {
static int leastFrequent(int arr[],int n)
{
// Insert all elements in hash.
Map count =
new HashMap();
for(int i = 0; i < n; i++)
{
int key = arr[i];
if(count.containsKey(key))
{
int freq = count.get(key);
freq++;
count.put(key,freq);
}
else
count.put(key,1);
}
// find min frequency.
int min_count = n+1, res = -1;
for(Entry val : count.entrySet())
{
if (min_count >= val.getValue())
{
res = val.getKey();
min_count = val.getValue();
}
}
return res;
}
// driver program
public static void main (String[] args) {
int arr[] = {1, 3, 2, 1, 2, 2, 3, 1};
int n = arr.length;
System.out.println(leastFrequent(arr,n));
}
}
// This code is contributed by Akash Singh.
输出:
3
时间复杂度: O(n Log n)
辅助空间: O(1)
一个有效的解决方案是使用散列。我们创建一个哈希表并将元素及其频率计数存储为键值对。最后我们遍历哈希表并打印具有最小值的键。
Java
//Java program to find the least frequent element
//in an array
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;
class GFG {
static int leastFrequent(int arr[],int n)
{
// Insert all elements in hash.
Map count =
new HashMap();
for(int i = 0; i < n; i++)
{
int key = arr[i];
if(count.containsKey(key))
{
int freq = count.get(key);
freq++;
count.put(key,freq);
}
else
count.put(key,1);
}
// find min frequency.
int min_count = n+1, res = -1;
for(Entry val : count.entrySet())
{
if (min_count >= val.getValue())
{
res = val.getKey();
min_count = val.getValue();
}
}
return res;
}
// driver program
public static void main (String[] args) {
int arr[] = {1, 3, 2, 1, 2, 2, 3, 1};
int n = arr.length;
System.out.println(leastFrequent(arr,n));
}
}
// This code is contributed by Akash Singh.
输出:
3
时间复杂度: O(n)
辅助空间: O(n)
有关更多详细信息,请参阅有关数组中最不频繁元素的完整文章!