📌  相关文章
📜  检查数组是否可以拆分为 K 个连续元素的子集

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

给定一个数组arr[]和整数K ,任务是将数组拆分为大小为K 的子集,使得每个子集由K个连续元素组成。

例子:

方法
请按照以下步骤解决问题:

  • 将所有数组元素的频率存储在 HashMap 中
  • 遍历HashMap
  • 对于HashMap 中存在的每个元素,检查是否所有出现的元素都可以与其下一个 (K – 1) 个连续元素一起分组到一个子集中。如果是,则在HashMap中相应地降低包含在子集中的元素的频率并继续前进。
  • 如果发现任何不能被分组为 K 个连续元素的子集的元素,则打印 False。否则打印 True。

下面是上述方法的实现:

C++
// C++ Program to implement the
// above approach
#include 
using namespace std;
 
// Function to check if a given array can
// be split into subsets of K consecutive
// elements
bool groupInKConsecutive(vector& arr,
                         int K)
{
    // Stores the frequencies of
    // array elements
    map count;
 
    for (int h : arr) {
        ++count[h];
    }
 
    // Traverse the map
    for (auto c : count) {
        int cur = c.first;
        int n = c.second;
 
        // Check if all its occurrences can
        // be grouped into K subsets
        if (n > 0) {
 
            // Traverse next K elements
            for (int i = 1; i < K; ++i) {
 
                // If the element is not
                // present in the array
                if (!count.count(cur + i)) {
                    return false;
                }
 
                count[cur + i] -= n;
 
                // If it cannot be split into
                // required number of subsets
                if (count[cur + i] < 0)
                    return false;
            }
        }
    }
 
    return true;
}
 
// Driver Code
int main()
{
    vector arr = { 1, 2, 3, 6, 2,
                        3, 4, 7, 8 };
    int k = 3;
    if (groupInKConsecutive(arr, k)) {
        cout << "True";
    }
    else {
        cout << "False";
    }
}


Java
// Java Program to implement the
// above approach
import java.util.*;
class GFG{
 
// Function to check if a given array can
// be split into subsets of K consecutive
// elements
static boolean groupInKConsecutive(int[] arr,
                                    int K)
{
    // Stores the frequencies of
    // array elements
    HashMap count = new HashMap();
 
    for (int h : arr)
    {
        if(count.containsKey(h))
            count.put(h, count.get(h) + 1);
        else
            count.put(h, 1);
    }
 
    // Traverse the map
    for (Map.Entry c : count.entrySet())
    {
        int cur = c.getKey();
        int n = c.getValue();
 
        // Check if all its occurrences can
        // be grouped into K subsets
        if (n > 0)
        {
 
            // Traverse next K elements
            for (int i = 1; i < K; ++i)
            {
 
                // If the element is not
                // present in the array
                if (!count.containsKey(cur + i))
                {
                    return false;
                }
 
                count.put(cur + i, count.get(cur + i) - n);
 
                // If it cannot be split into
                // required number of subsets
                if (count.get(cur + i) < 0)
                    return false;
            }
        }
    }
    return true;
}
 
// Driver Code
public static void main(String[] args)
{
    int[] arr = { 1, 2, 3, 6, 2,
                     3, 4, 7, 8 };
    int k = 3;
    if (groupInKConsecutive(arr, k))
    {
        System.out.print("True");
    }
    else
    {
        System.out.print("False");
    }
}
}
 
// This code contributed by sapnasingh4991


Python3
# Python3 program to implement the
# above approach
 
from collections import defaultdict
 
# Function to check if a given array can
# be split into subsets of K consecutive
# elements
def groupInKConsecutive(arr, K):
 
    # Stores the frequencies of
    # array elements
    count = defaultdict(int)
 
    for h in arr:
        count[h] += 1
 
    # Traverse the map
    for key, value in count.items():
        cur = key
        n = value
 
        # Check if all its occurrences can
        # be grouped into K subsets
        if (n > 0):
 
            # Traverse next K elements
            for i in range(1, K):
 
                # If the element is not
                # present in the array
                if ((cur + i) not in count):
                    return False
 
                count[cur + i] -= n
 
                # If it cannot be split into
                # required number of subsets
                if (count[cur + i] < 0):
                    return False
                     
    return True
 
# Driver Code
if __name__ == "__main__":
 
    arr = [ 1, 2, 3, 6, 2,
            3, 4, 7, 8 ]
    k = 3
     
    if (groupInKConsecutive(arr, k)):
        print("True")
    else:
        print("False")
 
# This code is contributed by chitranayal


C#
// C# program to implement the
// above approach
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
 
class GFG{
  
// Function to check if a given array can
// be split into subsets of K consecutive
// elements
static bool groupInKConsecutive(int[] arr,
                                int K)
{
     
    // Stores the frequencies of
    // array elements
    Dictionary count = new Dictionary();
  
    foreach(int h in arr)
    {
        if (count.ContainsKey(h))
            count[h]++;
        else
            count[h] = 1;
    }
  
    // Traverse the map
    foreach(int c in count.Keys.ToList())
    {
        int cur = c;
        int n = count;
         
        // Check if all its occurrences can
        // be grouped into K subsets
        if (n > 0)
        {
             
            // Traverse next K elements
            for(int i = 1; i < K; ++i)
            {
                 
                // If the element is not
                // present in the array
                if (!count.ContainsKey(cur + i))
                {
                    return false;
                }
  
                count[cur + i] -= n;
  
                // If it cannot be split into
                // required number of subsets
                if (count[cur + i] < 0)
                    return false;
            }
        }
    }
    return true;
}
  
// Driver Code
public static void Main(string[] args)
{
    int[] arr = { 1, 2, 3, 6, 2,
                  3, 4, 7, 8 };
    int k = 3;
    if (groupInKConsecutive(arr, k))
    {
        Console.Write("True");
    }
    else
    {
        Console.Write("False");
    }
}
}
 
// This code is contributed by rutvik_56


Javascript


输出:
True

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

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