📌  相关文章
📜  检查 K 个最少和最频繁的数组元素的总和是否相等

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

给定的阵列ARR []N个整数的,则任务是检查在K最频繁的数组元素的总和与在阵列ARR [] k个最低频繁数组元素的总和相等或没有。如果发现为true ,则打印Yes 。否则,打印No

例子:

方法:给定的问题可以通过使用带有频率索引的哈希找到 K 个最频繁的元素来解决,并且根据频率数组找到 K 个最频繁元素的总和等于数组中 K 个最不频繁元素的总和arr[ ] 。请按照以下步骤解决问题:

  • 初始化一个无序映射,比如M来计算每个数组元素的频率。
  • 迭代范围[0, N]并将每个数组元素的频率存储在无序映射M 中
  • 初始化大小为N + 1的二维向量freq以将给定频率的元素存储在映射M 中
  • 迭代范围[0, N]并执行以下步骤:
    • 将变量f初始化为arr[i]的频率M[arr[i]]
    • 如果f不等于-1 ,则将元素arr[i]推入频率f的向量freq并将m[arr[i]]的值设置为-1
  • 将变量count初始化为0以跟踪 K 个最频繁的元素和 K 个最不频繁的数组元素。
  • 将变量kleastfreqelem初始化为0以存储 K 个最不频繁的数组元素的总和。
  • 使用变量i在范围[0, N] 上迭代并执行以下步骤:
    • 迭代范围[0, freq[i]]并执行以下步骤:
      • freq[i][j]的值添加到变量kleastfreqelem并将count的值增加1
      • 如果计数等于K,则跳出循环。
    • 如果计数等于K,则中断循环。
  • 计数值设置0
  • 将变量kmostfreqelem初始化为0以存储数组arr[]的 K 个最低频率元素的总和。
  • 使用变量i在范围[N-1, 0] 上迭代并执行以下步骤:
    • 迭代范围[0, freq[i]]并执行以下步骤:
      • freq[i][j]的值添加到变量kmostfreqelem并将count的值增加1
      • 如果计数等于K ,则跳出循环。
    • 如果计数等于K ,则跳出循环。
  • 如果kmostfreqelem的值等于kleastelem ,则打印Yes 。否则,打印No

下面是上述方法的实现。

C++
// C++ program for the above approach
 
#include 
using namespace std;
 
// Function to compare the sum of K
// most and least occurrences
string checkSum(int arr[], int n, int k)
{
    // Stores frequency of array element
    unordered_map m;
    for (int i = 0; i < n; i++)
        m[arr[i]]++;
 
    // Stores the frequencies as indexes
    // and putelements with the frequency
    // in a vector
    vector freq[n + 1];
    for (int i = 0; i < n; i++) {
 
        // Find the frequency
        int f = m[arr[i]];
 
        if (f != -1) {
 
            // Insert in the vector
            freq[f].push_back(arr[i]);
            m[arr[i]] = -1;
        }
    }
 
    // Stores the count of elements
    int count = 0;
 
    int kleastfreqsum = 0;
 
    // Traverse the frequency array
    for (int i = 0; i <= n; i++) {
 
        // Find the kleastfreqsum
        for (int x : freq[i]) {
            kleastfreqsum += x;
            count++;
            if (count == k)
                break;
        }
 
        // If the count is K, break
        if (count == k)
            break;
    }
 
    // Reinitilize the count to zero
    count = 0;
 
    int kmostfreqsum = 0;
 
    // Traverse the frequency
    for (int i = n; i >= 0; i--) {
 
        // Find the kmostfreqsum
        for (int x : freq[i]) {
            kmostfreqsum += x;
            count++;
            if (count == k)
                break;
        }
 
        // If the count is K, break
        if (count == k)
            break;
    }
 
    // Comparing the sum
    if (kleastfreqsum == kmostfreqsum)
        return "Yes";
 
    // Otherwise, return No
    return "No";
}
 
// Driver Code
int main()
{
    int arr[] = { 3, 2, 1, 2, 3, 3, 4 };
    int N = sizeof(arr) / sizeof(arr[0]);
    int K = 2;
 
    cout << checkSum(arr, N, K);
 
    return 0;
}


Java
// Java program for the above approach
import java.util.*;
 
class GFG
{
 
// Function to compare the sum of K
// most and least occurrences
static String checkSum(int arr[], int n, int k)
{
   
    // Stores frequency of array element
    HashMap m = new HashMap();
    for (int i = 0; i < n; i++)
        if(m.containsKey(arr[i])){
            m.put(arr[i], m.get(arr[i])+1);
        }
        else{
            m.put(arr[i], 1);
        }
 
    // Stores the frequencies as indexes
    // and putelements with the frequency
    // in a vector
    Vector []freq = new Vector[n + 1];
    for (int i = 0; i < freq.length; i++)
        freq[i] = new Vector();
    for (int i = 0; i < n; i++) {
 
        // Find the frequency
        int f = m.get(arr[i]);
 
        if (f != -1) {
 
            // Insert in the vector
            freq[f].add(arr[i]);
            m.put(arr[i], -1);
        }
    }
 
    // Stores the count of elements
    int count = 0;
 
    int kleastfreqsum = 0;
 
    // Traverse the frequency array
    for (int i = 0; i <= n; i++) {
 
        // Find the kleastfreqsum
        for (int x : freq[i]) {
            kleastfreqsum += x;
            count++;
            if (count == k)
                break;
        }
 
        // If the count is K, break
        if (count == k)
            break;
    }
 
    // Reinitilize the count to zero
    count = 0;
 
    int kmostfreqsum = 0;
 
    // Traverse the frequency
    for (int i = n; i >= 0; i--) {
 
        // Find the kmostfreqsum
        for (int x : freq[i]) {
            kmostfreqsum += x;
            count++;
            if (count == k)
                break;
        }
 
        // If the count is K, break
        if (count == k)
            break;
    }
 
    // Comparing the sum
    if (kleastfreqsum == kmostfreqsum)
        return "Yes";
 
    // Otherwise, return No
    return "No";
}
 
// Driver Code
public static void main(String[] args)
{
    int arr[] = { 3, 2, 1, 2, 3, 3, 4 };
    int N = arr.length;
    int K = 2;
 
    System.out.print(checkSum(arr, N, K));
}
}
 
// This code is contributed by 29AjayKumar.


Python3
# Python3 program for the above approach
 
# Function to compare the sum of K
# most and least occurrences
def checkSum(arr, n, k):
     
    # Stores frequency of array element
    m = {}
     
    for i in range(n):
        if arr[i] in m:
            m[arr[i]] += 1
        else:
            m[arr[i]] = 1
 
    # Stores the frequencies as indexes
    # and putelements with the frequency
    # in a vector
    freq = [[] for i in range(n + 1)]
     
    for i in range(n):
         
        # Find the frequency
        f = m[arr[i]]
 
        if (f != -1):
 
            # Insert in the vector
            freq[f].append(arr[i])
            m[arr[i]] = -1
 
    # Stores the count of elements
    count = 0
 
    kleastfreqsum = 0
 
    # Traverse the frequency array
    for i in range(n + 1):
         
        # Find the kleastfreqsum
        for x in freq[i]:
            kleastfreqsum += x
            count += 1
             
            if (count == k):
                break
 
        # If the count is K, break
        if (count == k):
            break
 
    # Reinitilize the count to zero
    count = 0
 
    kmostfreqsum = 0
 
    # Traverse the frequency
    i = n
     
    while (i >= 0):
         
        # Find the kmostfreqsum
        for x in freq[i]:
            kmostfreqsum += x
            count += 1
             
            if (count == k):
                break
             
        i -= 1
 
        # If the count is K, break
        if (count == k):
            break
 
    # Comparing the sum
    if (kleastfreqsum == kmostfreqsum):
        return "Yes"
 
    # Otherwise, return No
    return "No"
 
# Driver Code
if __name__ == '__main__':
     
    arr = [ 3, 2, 1, 2, 3, 3, 4 ]
    N = len(arr)
    K = 2
     
    print(checkSum(arr, N, K))
 
# This code is contributed by SURENDRA_GANGWAR


Javascript


输出:
Yes

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

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