📌  相关文章
📜  包含给定数字正好K次的子数组的计数

📅  最后修改于: 2021-06-25 21:06:15             🧑  作者: Mango

给定N个元素组成的数组A [] ,其值从1到N具有重复项,则任务是找到包含给定数量num的子数组的总数,精确地是K次。

例子:

天真的方法:一个简单的解决方案是生成给定数组的所有子数组,并对给定数量恰好出现K次的子数组的数量进行计数。

时间复杂度: O(N 2 ) ,其中N是给定数组的大小。

高效方法:

  • 存储包含给定数字num索引
  • 遍历indexs []数组,并计算每K个索引可能的子数组数。
  • 任何Knum索引的可能子数组数目等于
  • 所有这些子数组的计数给出了给定数组中所有可能的子数组的计数。

下面是上述方法的实现:

C++
// C++ program to count subarrays
// which contains a given number
// exactly K times
 
#include 
using namespace std;
 
// Function to return
// the count of subarrays
// which contains given
// number exactly K times
int countSubarrays(int A[], int num,
                   int K, int size)
{
    // Store the indices
    // containing num
    vector indices;
    for (int i = 0; i < size; i++) {
        if (A[i] == num)
            indices.push_back(i);
    }
 
    // If the occurence of num
    // in the entire array
    // is less than K
    if (indices.size() < K)
 
        // No such subarrays are possible
        return 0;
 
    // Store the previous
    // index of num
    int prev = -1;
 
    // Store the count of
    // total subarrays
    int ans = 0;
 
    // Store the count of
    // subarrays for current
    // K occurences
    int ctr = 0;
 
    for (int i = 0;
         i <= indices.size() - K;
         i++) {
 
        ctr = indices[i] - prev;
 
        if (i < indices.size() - K) {
 
            ctr *= (indices[i + K]
                    - indices[i + K - 1]);
        }
        else {
            ctr *= ((size - 1)
                    - indices[i + K - 1] + 1);
        }
 
        ans += ctr;
        prev = indices[i];
    }
 
    return ans;
}
 
// Driver code
int main()
{
    int A[] = { 1, 5, 3, 5, 7, 5, 6,
                5, 10, 5, 12, 5 };
 
    int num = 5;
 
    int K = 3;
 
    int size = sizeof(A) / sizeof(int);
 
    cout << countSubarrays(A, num, K, size);
 
    return 0;
}


Java
// Java program to count subarrays
// which contains a given number
// exactly K times
 
import java.util.*;
public class Main {
 
    // Function to return
    // the count of subarrays
    // which contains given
    // number exactly K times
    public static int countSubarrays(
        int A[], int num,
        int K, int size)
    {
        // Store the indices
        // containing num
        ArrayList indices
            = new ArrayList();
 
        for (int i = 0; i < size; i++) {
            if (A[i] == num) {
                indices.add(i);
            }
        }
 
        if (indices.size() < K) {
            return 0;
        }
 
        // Store the previous
        // index of num
        int prev = -1;
 
        // Store the count of
        // total subarrays
        int ans = 0;
 
        // Store the count of
        // subarrays for current
        // K occurences
        int ctr = 0;
 
        for (int i = 0;
             i <= indices.size() - K;
             i++) {
 
            ctr = indices.get(i) - prev;
 
            if (i < indices.size() - K) {
 
                ctr *= (indices.get(i + K)
                        - indices.get(i + K - 1));
            }
            else {
                ctr *= ((size - 1)
                        - indices.get(i + K - 1) + 1);
            }
 
            ans += ctr;
            prev = indices.get(i);
        }
 
        return ans;
    }
 
    // Driver code
    public static void main(String[] args)
    {
 
        int A[] = { 1, 5, 3, 5, 7, 5,
                    6, 5, 10, 5, 12, 5 };
 
        int num = 5;
 
        int K = 3;
 
        int size = A.length;
 
        System.out.println(
            countSubarrays(A, num, K, size));
    }
}


Python3
# Python3 program to
# count subarrays which
# contains a given number
# exactly K times
 
# Function to return
# the count of subarrays
# which contains given
# number exactly K times
def countSubarrays(A, num,
                   K, size):
  # Store the indices
  # containing num
  indices = []
  for i in range (size):
    if (A[i] == num):
      indices.append(i)
       
  # If the occurence of num
  # in the entire array
  # is less than K
  if (len(indices) < K):
     
    # No such subarrays are possible
    return 0
   
  # Store the previous
  # index of num
  prev = -1
 
  # Store the count of
  # total subarrays
  ans = 0
 
  # Store the count of
  # subarrays for current
  # K occurences
  ctr = 0
   
  for i in range (len(indices) - K + 1):
    ctr = indices[i] - prev
    if (i < len(indices) - K):
      ctr *= (indices[i + K] -
              indices[i + K - 1])       
    else:
      ctr *= ((size - 1) -
               indices[i + K - 1] + 1)
    ans += ctr
    prev = indices[i]
  return ans
 
# Driver code
if __name__ == "__main__":
  A = [1, 5, 3, 5, 7, 5,
       6, 5, 10, 5, 12, 5]
  num = 5
  K = 3
  size = len(A)
  print(countSubarrays(A, num, K, size))
     
# This code is contributed by Chitranayal


C#
// C# program to count subarrays
// which contains a given number
// exactly K times
using System;
using System.Collections;
using System.Collections.Generic;
 
class GFG{
 
// Function to return the count of subarrays
// which contains given number exactly K times
public static int countSubarrays(int[] A, int num,
                                 int K, int size)
{
     
    // Store the indices
    // containing num
    ArrayList indices = new ArrayList();
 
    for(int i = 0; i < size; i++)
    {
        if (A[i] == num)
        {
            indices.Add(i);
        }
    }
 
    if (indices.Count < K)
    {
        return 0;
    }
 
    // Store the previous
    // index of num
    int prev = -1;
 
    // Store the count of
    // total subarrays
    int ans = 0;
 
    // Store the count of
    // subarrays for current
    // K occurences
    int ctr = 0;
 
    for(int i = 0;
            i <= indices.Count - K;
            i++)
    {
        ctr = (int)indices[i] - prev;
        if (i < indices.Count - K)
        {
            ctr *= ((int)indices[i + K] -
                    (int)indices[i + K - 1]);
        }
        else
        {
            ctr *= ((size - 1) -
                    (int)indices[i + K - 1] + 1);
        }
        ans += ctr;
        prev = (int)indices[i];
    }
    return ans;
}
 
// Driver code
static public void Main()
{
    int[] A = { 1, 5, 3, 5, 7, 5,
                6, 5, 10, 5, 12, 5 };
 
    int num = 5;
    int K = 3;
    int size = A.Length;
 
    Console.WriteLine(countSubarrays(A, num, K, size));
}
}
 
// This code is contributed by akhilsaini


Javascript


输出:
14

时间复杂度: O(N) ,其中N是数组的大小。
空间复杂度: O(N)

如果您希望与行业专家一起参加现场课程,请参阅《 Geeks现场课程》和《 Geeks现场课程美国》。