给定一个由N个元素组成的数组A。在数组中找到最小值的频率。
例子:
Input : N = 5, arr[] = {3, 2, 3, 4, 4}
Output : 1
The smallest element in the array is 2
and it occurs only once.
Input : N = 6, arr[] = {4, 3, 5, 3, 3, 6}
Output : 3
The smallest element in the array is 3
and it occurs 3 times.
简单方法:一个简单的方法是在第一次遍历中首先找到数组中的最小元素。然后再次遍历数组,找到最小元素的出现次数。
高效的方法:高效的方法是一次遍历。
让我们假设第一个元素是当前最小值,因此当前最小值的频率将是1。现在让我们遍历数组(从1到N),我们遇到2种情况:
- 当前元素小于我们的当前最小值:我们将当前最小值更改为等于当前元素,并且由于这是我们第一次遇到此元素,因此将其设为频率1。
- 当前元素等于当前最小值:我们增加当前最小值的频率。
下面是上述方法的实现:
C++
// C++ program to find the frequency of
// minimum element in the array
#include
using namespace std;
// Function to find the frequency of the
// smallest value in the array
int frequencyOfSmallest(int n, int arr[])
{
int mn = arr[0], freq = 1;
for (int i = 1; i < n; i++) {
// If current element is smaller
// than minimum
if (arr[i] < mn) {
mn = arr[i];
freq = 1;
}
// If current element is equal
// to smallest
else if (arr[i] == mn)
freq++;
}
return freq;
}
// Driver Code
int main()
{
int N = 5;
int arr[] = { 3, 2, 3, 4, 4 };
cout << frequencyOfSmallest(N, arr);
return 0;
}
Java
// Java program to find the frequency of
// minimum element in the array
import java.io.*;
class GFG
{
// Function to find the frequency of the
// smallest value in the array
static int frequencyOfSmallest(int n, int arr[])
{
int mn = arr[0], freq = 1;
for (int i = 1; i < n; i++)
{
// If current element is smaller
// than minimum
if (arr[i] < mn)
{
mn = arr[i];
freq = 1;
}
// If current element is equal
// to smallest
else if (arr[i] == mn)
freq++;
}
return freq;
}
// Driver Code
public static void main (String[] args)
{
int N = 5;
int arr[] = { 3, 2, 3, 4, 4 };
System.out.println (frequencyOfSmallest(N, arr));
}
}
// This code is contributed by Tushil.
Python3
# Python 3 program to find the frequency of
# minimum element in the array
# Function to find the frequency of the
# smallest value in the array
def frequencyOfSmallest(n,arr):
mn = arr[0]
freq = 1
for i in range(1,n):
# If current element is smaller
# than minimum
if (arr[i] < mn):
mn = arr[i]
freq = 1
# If current element is equal
# to smallest
elif(arr[i] == mn):
freq += 1
return freq
# Driver Code
if __name__ == '__main__':
N = 5
arr = [3, 2, 3, 4, 4]
print(frequencyOfSmallest(N, arr))
# This code is contributed by
# Surendra_Gangwar
C#
// C# program to find the frequency of
// minimum element in the array
using System;
class GFG
{
// Function to find the frequency of the
// smallest value in the array
static int frequencyOfSmallest(int n, int []arr)
{
int mn = arr[0], freq = 1;
for (int i = 1; i < n; i++)
{
// If current element is smaller
// than minimum
if (arr[i] < mn)
{
mn = arr[i];
freq = 1;
}
// If current element is equal
// to smallest
else if (arr[i] == mn)
freq++;
}
return freq;
}
// Driver Code
public static void Main()
{
int N = 5;
int []arr = { 3, 2, 3, 4, 4 };
Console.WriteLine(frequencyOfSmallest(N, arr));
}
}
// This code is contributed by Ryuga
PHP
输出:
1
时间复杂度: O(N)