📌  相关文章
📜  最小元素正好重复“k”次(不限于小范围)

📅  最后修改于: 2021-10-27 07:44:14             🧑  作者: Mango

给定一个大小为 n 的数组,目标是找出恰好重复 ‘k’ 次的最小数字,其中 k > 0?

例子:

Input : a[] = {2, 1, 3, 1, 2, 2}
        k = 3
Output : 2

Input : a[] = {3, 4, 3, 2, 1, 5, 5} 
        k = 2
Output : 3
Explanation: As 3 is smaller than 5. 
So 3 should be printed.

我们在下面的帖子中讨论了这个问题的不同解决方案。
数组中精确重复 ‘k’ 次的最小元素
上面讨论的解决方案要么仅限于在超过线性时间内的小范围工作。在这篇文章中,讨论了一个基于散列的解决方案,该解决方案在 O(n) 时间内工作并且适用于任何范围。下面是抽象步骤。
1) 创建一个哈希图来存储元素及其频率。
2) 遍历给定数组。对于遍历的每个元素,增加其频率。
3) 遍历hash map,打印频率为k的最小元素。

C++
// C++ program to find the smallest element
// with frequency exactly k.
#include 
using namespace std;
 
int smallestKFreq(int a[], int n, int k)
{
    unordered_map m;
 
    // Map is used to store the count of
    // elements present in the array
    for (int i = 0; i < n; i++)
        m[a[i]]++;
 
    // Traverse the map and find minimum
    // element with frequency k.
    int res = INT_MAX;
    for (auto it = m.begin(); it != m.end(); ++it)
        if (it->second == k)
           res = min(res, it->first);
 
    return (res != INT_MAX)? res : -1;
}
 
// Driver code
int main()
{
    int arr[] = { 2, 2, 1, 3, 1 };
    int k = 2;
    int n = sizeof(arr) / (sizeof(arr[0]));
    cout << smallestKFreq(arr, n, k);
    return 0;
}


Java
// Java program to find the smallest element
// with frequency exactly k.
import java.util.*;
 
class GFG {
      
    public static int smallestKFreq(int a[], int n, int k)
    {
        HashMap m = new HashMap();
      
        // Map is used to store the count of
        // elements present in the array
        for (int i = 0; i < n; i ++)
             
            if (m.containsKey(a[i]))
                m.put(a[i], m.get(a[i]) + 1);
         
           else m.put(a[i], 1);
      
        // Traverse the map and find minimum
        // element with frequency k.
        int res = Integer.MAX_VALUE;
        Set s = m.keySet();
         
        for (int temp : s)
            if (m.get(temp) == k)
               res = Math.min(res, temp);
      
        return (res != Integer.MAX_VALUE)? res : -1;
    }
     
    /* Driver program to test above function */
    public static void main(String[] args)
    {
        int arr[] = { 2, 2, 1, 3, 1 };
        int k = 2;
         
        System.out.println(smallestKFreq(arr, arr.length, k));
      
    }
  }
// This code is contributed by Arnav Kr. Mandal.


Python3
from collections import defaultdict
import sys
 
# Python program to find the smallest element
# with frequency exactly k.
def smallestKFreq(arr, n, k):
    mp = defaultdict(lambda : 0)
 
 
    # Map is used to store the count of
    # elements present in the array
    for i in range(n):
        mp[arr[i]] += 1
 
    # Traverse the map and find minimum
    # element with frequency k.
    res = sys.maxsize
    res1 = sys.maxsize
 
    for key,values in mp.items():
 
        if values == k:
            res = min(res, key)
    return res if res != res1 else -1
 
# Driver code
arr = [2, 2, 1, 3, 1]
k = 2
n = len(arr)
print(smallestKFreq(arr, n, k))
 
# This code is contributed by Shrikant13


C#
// C# program to find the smallest element
// with frequency exactly k.
using System;
using System.Linq;
using System.Collections.Generic;
     
class GFG
{
     
    public static int smallestKFreq(int []a, int n, int k)
    {
        Dictionary m = new Dictionary();
     
        // Map is used to store the count of
        // elements present in the array
        for (int i = 0; i < n; i ++)
             
            if (m.ContainsKey(a[i]))
            {
                var v = m[a[i]];
                m.Remove(a[i]);
                m.Add(a[i],v + 1);
            }
        else m.Add(a[i], 1);
     
        // Traverse the map and find minimum
        // element with frequency k.
        int res = int.MaxValue;
        HashSet s = new HashSet(m.Keys.ToArray());
         
        foreach (int temp in s)
            if (m[temp] == k)
            res = Math.Min(res, temp);
     
        return (res != int.MaxValue)? res : -1;
    }
     
    /* Driver code */
    public static void Main(String[] args)
    {
        int []arr = { 2, 2, 1, 3, 1 };
        int k = 2;
         
        Console.WriteLine(smallestKFreq(arr, arr.Length, k));
     
    }
}
 
// This code is contributed by Rajput-Ji


Javascript


输出:

1

如果您希望与专家一起参加现场课程,请参阅DSA 现场工作专业课程学生竞争性编程现场课程