📌  相关文章
📜  检查给定数组中每个元素的频率是否唯一

📅  最后修改于: 2021-04-27 19:38:47             🧑  作者: Mango

给定一个由N个正整数组成的数组arr [] ,该整数在1到N的范围内,任务是检查数组中元素的频率是否唯一。如果所有频率都是唯一的,则打印“是” ,否则打印“否”

例子:

天真的方法:这个想法是检查从1到N的每个数字是否存在于数组中。如果是,则计算该元素在阵列中的频率,并将该频率存储在阵列中。最后,只需检查数组中是否有重复的元素并相应地打印输出即可。

时间复杂度: O(N 2 )
辅助空间: O(N)

高效的方法:想法是使用哈希。步骤如下:

  1. 遍历给定的数组arr []并将每个元素的频率存储在Map中。
  2. 现在遍历地图,检查任何元素的计数是否多次出现。
  3. 如果以上步骤中任何元素的数量大于一个,则打印“否” ,否则打印“是”

下面是上述方法的实现:

C++
// C++ code for the above approach
#include 
using namespace std;
 
// Function to check whether the
// frequency of elements in array
// is unique or not.
bool checkUniqueFrequency(int arr[],
                          int n)
{
 
    // Freq map will store the frequency
    // of each element of the array
    unordered_map freq;
 
    // Store the frequency of each
    // element from the array
    for (int i = 0; i < n; i++) {
        freq[arr[i]]++;
    }
 
    unordered_set uniqueFreq;
 
    // Check whether frequency of any
    // two or more elements are same
    // or not. If yes, return false
    for (auto& i : freq) {
        if (uniqueFreq.count(i.second))
            return false;
        else
            uniqueFreq.insert(i.second);
    }
 
    // Return true if each
    // frequency is unique
    return true;
}
 
// Driver Code
int main()
{
    // Given array arr[]
    int arr[] = { 1, 1, 2, 5, 5 };
    int n = sizeof arr / sizeof arr[0];
 
    // Function Call
    bool res = checkUniqueFrequency(arr, n);
 
    // Print the result
    if (res)
        cout << "Yes" << endl;
    else
        cout << "No" << endl;
    return 0;
}


Java
// Java code for the above approach
import java.util.*;
 
class GFG{
 
// Function to check whether the
// frequency of elements in array
// is unique or not.
static boolean checkUniqueFrequency(int arr[],
                                    int n)
{
     
    // Freq map will store the frequency
    // of each element of the array
    HashMap freq = new HashMap();
 
    // Store the frequency of each
    // element from the array
    for(int i = 0; i < n; i++)
    {
        if(freq.containsKey(arr[i]))
        {
            freq.put(arr[i], freq.get(arr[i]) + 1);
        }else
        {
            freq.put(arr[i], 1);
        }
    }
 
    HashSet uniqueFreq = new HashSet();
 
    // Check whether frequency of any
    // two or more elements are same
    // or not. If yes, return false
    for(Map.Entry i : freq.entrySet())
    {
        if (uniqueFreq.contains(i.getValue()))
            return false;
        else
            uniqueFreq.add(i.getValue());
    }
 
    // Return true if each
    // frequency is unique
    return true;
}
 
// Driver Code
public static void main(String[] args)
{
     
    // Given array arr[]
    int arr[] = { 1, 1, 2, 5, 5 };
    int n = arr.length;
 
    // Function call
    boolean res = checkUniqueFrequency(arr, n);
 
    // Print the result
    if (res)
        System.out.print("Yes" + "\n");
    else
        System.out.print("No" + "\n");
}
}
 
// This code is contributed by PrinciRaj1992


Python3
# Python3 code for
# the above approach
from collections import defaultdict
 
# Function to check whether the
# frequency of elements in array
# is unique or not.
def checkUniqueFrequency(arr, n):
  
    # Freq map will store the frequency
    # of each element of the array
    freq = defaultdict (int)
  
    # Store the frequency of each
    # element from the array
    for i in range (n):
        freq[arr[i]] += 1
  
    uniqueFreq = set([])
  
    # Check whether frequency of any
    # two or more elements are same
    # or not. If yes, return false
    for i in freq:
        if (freq[i] in uniqueFreq):
            return False
        else:
            uniqueFreq.add(freq[i])
  
    # Return true if each
    # frequency is unique
    return True
  
# Driver Code
if __name__ == "__main__":
 
    # Given array arr[]
    arr = [1, 1, 2, 5, 5]
    n = len(arr)
  
    # Function Call
    res = checkUniqueFrequency(arr, n)
  
    # Print the result
    if (res):
        print ("Yes")
    else:
        print ("No")
 
# This code is contributed by Chitranayal


C#
// C# code for the above approach
using System;
using System.Collections.Generic;
class GFG{
 
// Function to check whether the
// frequency of elements in array
// is unique or not.
static bool checkUniqueFrequency(int []arr,
                                 int n)
{
     
    // Freq map will store the frequency
    // of each element of the array
    Dictionary freq = new Dictionary();
 
    // Store the frequency of each
    // element from the array
    for(int i = 0; i < n; i++)
    {
        if(freq.ContainsKey(arr[i]))
        {
            freq[arr[i]] = freq[arr[i]] + 1;
        }else
        {
            freq.Add(arr[i], 1);
        }
    }
 
    HashSet uniqueFreq = new HashSet();
 
    // Check whether frequency of any
    // two or more elements are same
    // or not. If yes, return false
    foreach(KeyValuePair i in freq)
    {
        if (uniqueFreq.Contains(i.Value))
            return false;
        else
            uniqueFreq.Add(i.Value);
    }
 
    // Return true if each
    // frequency is unique
    return true;
}
 
// Driver Code
public static void Main(String[] args)
{
     
    // Given array []arr
    int []arr = { 1, 1, 2, 5, 5 };
    int n = arr.Length;
 
    // Function call
    bool res = checkUniqueFrequency(arr, n);
 
    // Print the result
    if (res)
        Console.Write("Yes" + "\n");
    else
        Console.Write("No" + "\n");
}
}
 
// This code is contributed by sapnasingh4991


输出:
No



时间复杂度: O(N),其中N是数组中元素的数量。
辅助空间: O(N)