📌  相关文章
📜  计算每个不同元素至少出现两次的子数组

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

给定一个大小为N的数组arr[] ,任务是计算给定数组中子数组的数量,使得这些子数组中的每个不同元素至少出现两次。

例子:

朴素的方法:解决这个问题最简单的方法是遍历数组并生成给定数组的所有可能子数组,对于每个子数组,检查子数组中的所有元素是否至少出现两次。如果发现为真,则增加计数。最后,打印获得的计数

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

高效的方法:优化上述方法的想法是使用哈希。请按照以下步骤解决问题:

  • 初始化一个变量,比如cntSub来存储子数组的计数,这样子数组中的每个元素至少出现两次。
  • 创建一个 Map,比如cntFreq ,以存储每个子数组的元素的频率。
  • 初始化一个变量,比如cntUnique ,以存储频率为1的子数组中元素的计数。
  • 遍历数组并生成所有可能的子数组。对于每个可能的子数组,存储数组中每个元素的频率并检查cntUnique的值是否0 。如果发现为真,则增加cntSub的值。
  • 最后,打印cntSub的值。

下面是上述方法的实现:

C++
// C++ program to implement
// the above approach
 
#include 
using namespace std;
 
// Function to get the count
// of subarrays having each
// element occurring at least twice
int cntSubarrays(int arr[], int N)
{
    // Stores count of subarrays
    // having each distinct element
    // occurring at least twice
    int cntSub = 0;
 
    // Stores count of unique
    // elements in a subarray
    int cntUnique = 0;
 
    // Store frequency of
    // each element of a subarray
    unordered_map cntFreq;
 
    // Traverse the given
    // array
    for (int i = 0; i < N;
         i++) {
 
        // Count frequency and
        // check conditions for
        // each subarray
        for (int j = i; j < N;
             j++) {
 
            // Update frequency
            cntFreq[arr[j]]++;
 
            // Check if frequency of
            // arr[j] equal to 1
            if (cntFreq[arr[j]]
                == 1) {
 
                // Update Count of
                // unique elements
                cntUnique++;
            }
            else if (cntFreq[arr[j]]
                     == 2) {
 
                // Update count of
                // unique elements
                cntUnique--;
            }
 
            // If each element of subarray
            // occurs at least twice
            if (cntUnique == 0) {
 
                // Update cntSub
                cntSub++;
            }
        }
 
        // Remove all elements
        // from the subarray
        cntFreq.clear();
 
        // Update cntUnique
        cntUnique = 0;
    }
    return cntSub;
}
 
// Driver Code
int main()
{
    int arr[] = { 1, 1, 2, 2, 2 };
    int N = sizeof(arr) / sizeof(arr[0]);
    cout << cntSubarrays(arr, N);
}


Java
// Java program to implement
// the above approach
import java.util.*;
 
class GFG{
   
// Function to get the count
// of subarrays having each
// element occurring at least twice
static int cntSubarrays(int arr[], int N)
{
     
    // Stores count of subarrays
    // having each distinct element
    // occurring at least twice
    int cntSub = 0;
 
    // Stores count of unique
    // elements in a subarray
    int cntUnique = 0;
 
    // Store frequency of
    // each element of a subarray
     Map cntFreq = new HashMap();
                                         
    // Traverse the given
    // array
    for(int i = 0; i < N; i++)
    {
         
        // Count frequency and
        // check conditions for
        // each subarray
        for(int j = i; j < N; j++)
        {
             
            // Update frequency
            cntFreq.put(arr[j],
                        cntFreq.getOrDefault(
                        arr[j], 0) + 1);
 
            // Check if frequency of
            // arr[j] equal to 1
            if (cntFreq.get(arr[j]) == 1)
            {
                 
                // Update Count of
                // unique elements
                cntUnique++;
            }
            else if (cntFreq.get(arr[j]) == 2)
            {
                 
                // Update count of
                // unique elements
                cntUnique--;
            }
 
            // If each element of subarray
            // occurs at least twice
            if (cntUnique == 0)
            {
                 
                // Update cntSub
                cntSub++;
            }
        }
 
        // Remove all elements
        // from the subarray
        cntFreq.clear();
 
        // Update cntUnique
        cntUnique = 0;
    }
    return cntSub;
}
 
// Driver Code
public static void main(String args[])
{
    int arr[] = { 1, 1, 2, 2, 2 };
    int N = arr.length;
     
    System.out.println(cntSubarrays(arr, N));
}
}
 
// This code is contributed by SURENDRA_GANGWAR


Python3
# Python3 program to implement
# the above approach
from collections import defaultdict
 
# Function to get the count
# of subarrays having each
# element occurring at least twice
def cntSubarrays(arr, N):
 
    # Stores count of subarrays
    # having each distinct element
    # occurring at least twice
    cntSub = 0
 
    # Stores count of unique
    # elements in a subarray
    cntUnique = 0
 
    # Store frequency of
    # each element of a subarray
    cntFreq = defaultdict(lambda : 0)
 
    # Traverse the given
    # array
    for i in range(N):
         
        # Count frequency and
        # check conditions for
        # each subarray
        for j in range(i, N):
             
            # Update frequency
            cntFreq[arr[j]] += 1
 
            # Check if frequency of
            # arr[j] equal to 1
            if (cntFreq[arr[j]] == 1):
 
                # Update Count of
                # unique elements
                cntUnique += 1
 
            elif (cntFreq[arr[j]] == 2):
                 
                # Update count of
                # unique elements
                cntUnique -= 1
 
            # If each element of subarray
            # occurs at least twice
            if (cntUnique == 0):
                 
                # Update cntSub
                cntSub += 1
 
        # Remove all elements
        # from the subarray
        cntFreq.clear()
 
        # Update cntUnique
        cntUnique = 0
 
    return cntSub
 
# Driver code
if __name__ == '__main__':
 
    arr = [ 1, 1, 2, 2, 2 ]
    N = len(arr)
     
    print(cntSubarrays(arr, N))
 
# This code is contributed by Shivam Singh


C#
// C# program to implement
// the above approach
using System;
using System.Collections.Generic;
 
class GFG{
 
// Function to get the count
// of subarrays having each
// element occurring at least twice
static int cntSubarrays(int[] arr, int N)
{
     
    // Stores count of subarrays
    // having each distinct element
    // occurring at least twice
    int cntSub = 0;
 
    // Stores count of unique
    // elements in a subarray
    int cntUnique = 0;
 
    // Store frequency of
    // each element of a subarray
    Dictionary cntFreq = new Dictionary();
                                              
    // Traverse the given
    // array
    for(int i = 0; i < N; i++)
    {
         
        // Count frequency and
        // check conditions for
        // each subarray
        for(int j = i; j < N; j++)
        {
             
            // Update frequency
            if (cntFreq.ContainsKey(arr[j]))
            {
                var val = cntFreq[arr[j]];
                cntFreq.Remove(arr[j]);
                cntFreq.Add(arr[j], val + 1);
            }
            else
            {
                cntFreq.Add(arr[j], 1);
            }
 
            // Check if frequency of
            // arr[j] equal to 1
            if (cntFreq[arr[j]] == 1)
            {
                 
                // Update Count of
                // unique elements
                cntUnique++;
            }
            else if (cntFreq[arr[j]] == 2)
            {
                 
                // Update count of
                // unique elements
                cntUnique--;
            }
 
            // If each element of subarray
            // occurs at least twice
            if (cntUnique == 0)
            {
                 
                // Update cntSub
                cntSub++;
            }
        }
 
        // Remove all elements
        // from the subarray
        cntFreq.Clear();
 
        // Update cntUnique
        cntUnique = 0;
    }
    return cntSub;
}
 
// Driver Code
public static void Main()
{
    int[] arr = { 1, 1, 2, 2, 2 };
    int N = arr.Length;
     
    Console.Write(cntSubarrays(arr, N));
}
}
 
// This code is contributed by subhammahato348


Javascript


输出:
6

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

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