📌  相关文章
📜  计数具有相等计数的 0 和 1 分隔的子数组

📅  最后修改于: 2021-09-04 08:04:31             🧑  作者: Mango

给定一个二进制数组arr[] ,任务是计算0 s 和1 s 计数相等的子数组的数量,并将所有0 s 和1 s 连续放置在该子数组中。

例子:

朴素的方法:最简单的方法是遍历给定的数组,对于每对不相等的相邻元素,迭代当前索引的左右,并检查10的计数是否相等。增加子数组的计数,直到发现为假。完成数组遍历后,打印子数组的总数。

下面是上述方法的实现:

C++
// C++ program for the above approach
 
#include 
using namespace std;
 
// Function to count subarrays
// having equal count of 0s and 1s
// with all 0s and all 1s grouped together
void countSubarrays(int A[], int N)
{
    // Stores the count of subarrays
    int ans = 0;
 
    for (int i = 0; i < N - 1; i++) {
 
        // If current element is different
        // from the next array element
        if (A[i] != A[i + 1]) {
 
            // Increment count
            ans++;
 
            // Count the frequency of
            // 1s and 0s
            for (int j = i - 1, k = i + 2;
                 j >= 0 && k < N
                 && A[j] == A[i]
                 && A[k] == A[i + 1];
                 j--, k++) {
 
                // Increment count
                ans++;
            }
        }
    }
 
    // Print the final count
    cout << ans << "\n";
}
 
// Driver Code
int main()
{
    int A[] = { 1, 1, 0, 0, 1, 0 };
    int N = sizeof(A) / sizeof(A[0]);
 
    // Function Call
    countSubarrays(A, N);
 
    return 0;
}


Java
// Java program for the above approach
import java.util.*;
 
class GFG
{
 
// Function to count subarrays
// having equal count of 0s and 1s
// with all 0s and all 1s grouped together
static void countSubarrays(int A[], int N)
{
   
    // Stores the count of subarrays
    int ans = 0;
 
    for (int i = 0; i < N - 1; i++)
    {
 
        // If current element is different
        // from the next array element
        if (A[i] != A[i + 1])
        {
 
            // Increment count
            ans++;
 
            // Count the frequency of
            // 1s and 0s
            for (int j = i - 1, k = i + 2;
                 j >= 0 && k < N
                 && A[j] == A[i]
                 && A[k] == A[i + 1];
                 j--, k++)
            {
 
                // Increment count
                ans++;
            }
        }
    }
 
    // Print the final count
    System.out.print(ans+ "\n");
}
 
// Driver Code
public static void main(String[] args)
{
    int A[] = { 1, 1, 0, 0, 1, 0 };
    int N = A.length;
 
    // Function Call
    countSubarrays(A, N);
}
}
 
// This code is contributed by shikhasingrajput


Python3
# Python3 program for the above approach
 
# Function to count subarrays
# having equal count of 0s and 1s
# with all 0s and all 1s grouped together
def countSubarrays(A, N) :
 
    # Stores the count of subarrays
    ans = 0;
 
    for i in range(N - 1) :
 
        # If current element is different
        # from the next array element
        if (A[i] != A[i + 1]) :
 
            # Increment count
            ans += 1;
 
            # Count the frequency of
            # 1s and 0s
            j = i - 1; k = i + 2;
            while (j >= 0 and k < N and A[j] == A[i] and A[k] == A[i + 1]) :
                 
                # Increment count
                ans += 1;
                 
                j -= 1;
                k += 1;
 
    # Print the final count
    print(ans);
 
# Driver Code
if __name__ == "__main__" :
 
    A = [ 1, 1, 0, 0, 1, 0 ];
    N = len(A);
 
    # Function Call
    countSubarrays(A, N);
 
    # This code is contributed by AnkitRai01


C#
// C# program for the above approach
using System;
  
class GFG{
  
// Function to count subarrays
// having equal count of 0s and 1s
// with all 0s and all 1s grouped together
static void countSubarrays(int[] A, int N)
{
     
    // Stores the count of subarrays
    int ans = 0;
  
    for(int i = 0; i < N - 1; i++)
    {
         
        // If current element is different
        // from the next array element
        if (A[i] != A[i + 1])
        {
  
            // Increment count
            ans++;
  
            // Count the frequency of
            // 1s and 0s
            for(int j = i - 1, k = i + 2;
                    j >= 0 && k < N &&
                       A[j] == A[i] &&
                       A[k] == A[i + 1];
                    j--, k++)
            {
                 
                // Increment count
                ans++;
            }
        }
    }
  
    // Print the final count
    Console.Write(ans + "\n");
}
  
// Driver Code
public static void Main()
{
    int[] A = { 1, 1, 0, 0, 1, 0 };
    int N = A.Length;
  
    // Function Call
    countSubarrays(A, N);
}
}
 
// This code is contributed by sanjoy_62


Javascript


C++
// C++ program for the above approach
#include 
using namespace std;
 
// Function to count subarrays
// having equal count of 0s and 1s
// with all 0s and all 1s grouped together
void countSubarrays(int A[], int N)
{
 
    // Stores the count
    int res = 0;
 
    // Initialize cur with first element
    int curr = A[0];
    vector cnt = {1};
    for (int c = 1; c < N; c++)
    {
 
        // If the next element is same
        // as the current element
        if (A == curr)
 
            // Increment count
            cnt[cnt.size() - 1]++;
        else
 
            // Update curr
            curr = A;
        cnt.push_back(1);
    }
 
    // Iterate over the array count
    for (int i = 1; i < cnt.size(); i++)
    {
 
        // Consider the minimum
        res += min(cnt[i - 1], cnt[i]);
    }
    cout << (res - 1);
}
 
// Driver code
int main()
{
    // Given arr[]
    int A[] = { 1, 1, 0, 0, 1, 0 };   
    int N = sizeof(A) / sizeof(A[0]);
   
    // Function Call
    countSubarrays(A, N);
    return 0;
}
 
// This code is contributed by divyesh072019


Java
import java.util.Vector;
 
// Java program for the above approach
class GFG {
   
    // Function to count subarrays
    // having equal count of 0s and 1s
    // with all 0s and all 1s grouped together
    static void countSubarrays(int[] A)
    {
 
        // Stores the count
        int res = 0;
 
        // Initialize cur with first element
        int curr = A[0];
        int[] cnt = new int[A.length];
        cnt[0] = 1;
        for (int c = 1; c < A.length; c++) {
 
            // If the next element is same
            // as the current element
            if (A == curr)
 
                // Increment count
 
                cnt++;
            else
 
                // Update curr
                curr = A;
            cnt = 1;
        }
 
        // Iterate over the array count
        for (int i = 1; i < cnt.length; i++) {
 
            // Consider the minimum
            res += Math.min(cnt[i - 1], cnt[i]);
        }
        System.out.println(res - 1);
    }
   
    // Driver code
    public static void main(String[] args)
    {
        // Given arr[]
        int[] A = { 1, 1, 0, 0, 1, 0 };
 
        // Function Call
        countSubarrays(A);
    }
}
 
// This code is contributed by 29AjayKumar


Python3
# Python3 program for the above approach
 
# Function to count subarrays
# having equal count of 0s and 1s
# with all 0s and all 1s grouped together
def countSubarrays(A):
     
    # Stores the count
    res = 0
     
    # Initialize cur with first element
    curr, cnt = A[0], [1]
    for c in A[1:]:
       
        # If the next element is same
        # as the current element
        if c == curr:
           
            # Increment count
            cnt[-1] += 1
        else:
           
            # Update curr
            curr = c
        cnt.append(1)
     
    # Iterate over the array count
    for i in range(1, len(cnt)):
       
        # Consider the minimum
        res += min(cnt[i - 1], cnt[i])
     
    print(res - 1)
 
# Given arr[]
A = [1, 1, 0, 0, 1, 0]
 
# Function Call
countSubarrays(A)


C#
// C# program for the above approach
using System;
 
class GFG{
   
// Function to count subarrays
// having equal count of 0s and 1s
// with all 0s and all 1s grouped together
static void countSubarrays(int[] A)
{
     
    // Stores the count
    int res = 0;
 
    // Initialize cur with first element
    int curr = A[0];
    int[] cnt = new int[A.Length];
    cnt[0] = 1;
     
    for(int c = 1; c < A.Length; c++)
    {
         
        // If the next element is same
        // as the current element
        if (A == curr)
 
            // Increment count
            cnt++;
        else
 
            // Update curr
            curr = A;
             
        cnt = 1;
    }
 
    // Iterate over the array count
    for(int i = 1; i < cnt.Length; i++)
    {
         
        // Consider the minimum
        res += Math.Min(cnt[i - 1], cnt[i]);
    }
    Console.WriteLine(res - 1);
}
 
// Driver code
public static void Main(String[] args)
{
     
    // Given []arr
    int[] A = { 1, 1, 0, 0, 1, 0 };
 
    // Function Call
    countSubarrays(A);
}
}
 
// This code is contributed by Amit Katiyar


Javascript


输出:
4

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

高效的方法:要优化上述方法,请按照以下步骤操作:

  • 初始化一个变量,比如res ,以存储子数组的计数。
  • 用数组的第一个值和数组cnt[]初始化一个变量,比如curr ,以跟踪连续的元素。
  • 遍历数组并执行以下步骤:
    • 如果当前元素等于curr ,则增加cnt[]的最后一个值。
    • 否则,将curr更新为当前元素并将1附加到数组cnt[]
  • 遍历数组cnt[]并找到相邻元素的最小值之和并将其添加到变量res 中。这确保了元素的频率相等。
  • 完成上述步骤后,将res的值打印为子数组的结果计数。

下面是上述方法的实现:

C++

// C++ program for the above approach
#include 
using namespace std;
 
// Function to count subarrays
// having equal count of 0s and 1s
// with all 0s and all 1s grouped together
void countSubarrays(int A[], int N)
{
 
    // Stores the count
    int res = 0;
 
    // Initialize cur with first element
    int curr = A[0];
    vector cnt = {1};
    for (int c = 1; c < N; c++)
    {
 
        // If the next element is same
        // as the current element
        if (A == curr)
 
            // Increment count
            cnt[cnt.size() - 1]++;
        else
 
            // Update curr
            curr = A;
        cnt.push_back(1);
    }
 
    // Iterate over the array count
    for (int i = 1; i < cnt.size(); i++)
    {
 
        // Consider the minimum
        res += min(cnt[i - 1], cnt[i]);
    }
    cout << (res - 1);
}
 
// Driver code
int main()
{
    // Given arr[]
    int A[] = { 1, 1, 0, 0, 1, 0 };   
    int N = sizeof(A) / sizeof(A[0]);
   
    // Function Call
    countSubarrays(A, N);
    return 0;
}
 
// This code is contributed by divyesh072019

Java

import java.util.Vector;
 
// Java program for the above approach
class GFG {
   
    // Function to count subarrays
    // having equal count of 0s and 1s
    // with all 0s and all 1s grouped together
    static void countSubarrays(int[] A)
    {
 
        // Stores the count
        int res = 0;
 
        // Initialize cur with first element
        int curr = A[0];
        int[] cnt = new int[A.length];
        cnt[0] = 1;
        for (int c = 1; c < A.length; c++) {
 
            // If the next element is same
            // as the current element
            if (A == curr)
 
                // Increment count
 
                cnt++;
            else
 
                // Update curr
                curr = A;
            cnt = 1;
        }
 
        // Iterate over the array count
        for (int i = 1; i < cnt.length; i++) {
 
            // Consider the minimum
            res += Math.min(cnt[i - 1], cnt[i]);
        }
        System.out.println(res - 1);
    }
   
    // Driver code
    public static void main(String[] args)
    {
        // Given arr[]
        int[] A = { 1, 1, 0, 0, 1, 0 };
 
        // Function Call
        countSubarrays(A);
    }
}
 
// This code is contributed by 29AjayKumar

蟒蛇3

# Python3 program for the above approach
 
# Function to count subarrays
# having equal count of 0s and 1s
# with all 0s and all 1s grouped together
def countSubarrays(A):
     
    # Stores the count
    res = 0
     
    # Initialize cur with first element
    curr, cnt = A[0], [1]
    for c in A[1:]:
       
        # If the next element is same
        # as the current element
        if c == curr:
           
            # Increment count
            cnt[-1] += 1
        else:
           
            # Update curr
            curr = c
        cnt.append(1)
     
    # Iterate over the array count
    for i in range(1, len(cnt)):
       
        # Consider the minimum
        res += min(cnt[i - 1], cnt[i])
     
    print(res - 1)
 
# Given arr[]
A = [1, 1, 0, 0, 1, 0]
 
# Function Call
countSubarrays(A)

C#

// C# program for the above approach
using System;
 
class GFG{
   
// Function to count subarrays
// having equal count of 0s and 1s
// with all 0s and all 1s grouped together
static void countSubarrays(int[] A)
{
     
    // Stores the count
    int res = 0;
 
    // Initialize cur with first element
    int curr = A[0];
    int[] cnt = new int[A.Length];
    cnt[0] = 1;
     
    for(int c = 1; c < A.Length; c++)
    {
         
        // If the next element is same
        // as the current element
        if (A == curr)
 
            // Increment count
            cnt++;
        else
 
            // Update curr
            curr = A;
             
        cnt = 1;
    }
 
    // Iterate over the array count
    for(int i = 1; i < cnt.Length; i++)
    {
         
        // Consider the minimum
        res += Math.Min(cnt[i - 1], cnt[i]);
    }
    Console.WriteLine(res - 1);
}
 
// Driver code
public static void Main(String[] args)
{
     
    // Given []arr
    int[] A = { 1, 1, 0, 0, 1, 0 };
 
    // Function Call
    countSubarrays(A);
}
}
 
// This code is contributed by Amit Katiyar

Javascript


输出:
4

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

如果您想与行业专家一起参加直播课程,请参阅Geeks Classes Live