📌  相关文章
📜  从二进制数组中的每个索引开始的最长交替子数组

📅  最后修改于: 2021-05-07 07:40:06             🧑  作者: Mango

给定一个仅包含0和1的数组。对于每个索引“ i ”(0索引),找到从“ i ”到“ j ”的最长交替子数组的长度,即i i = j a i..j 。交替子数组意味着任何两个相邻元素都应不同。
例子:

Input: arr[] = {1, 0, 1, 0, 0, 1}
Output: 4 3 2 1 2 1 
Explanation
Length for index '0': {1 0 1 0} => 4
Length for index '1': {0 1 0}   => 3
Length for index '2': {1 0}     => 2
Length for index '3': {0}       => 1
Length for index '4': {0 1}     => 2
Length for index '5': {1}       => 1

一种简单的方法是通过使用两个“ for循环”来查找每个索引的长度来迭代每个索引。外循环选择起点“ i”,内循环考虑从“ i”开始的所有子阵列。该方法的时间复杂度为O(n 2 ),不足以获取较大的’n’值。
更好的方法是使用动态编程。首先,让我们看看如何检查交替子数组。要检查两个元素是否交替,我们可以简单地对两个元素进行XOR(Ex-OR),然后与“ 0”和“ 1”进行比较。

  • 如果XOR为0,则表示两个数字不是交替的(相等的元素)。
  • 如果XOR为’1’,则表示两者是交替的(不同的元素)

len [i]表示从位置“ i”开始的交替子数组的长度。如果arr [i]和arr [i + 1]的值不同,则len [i]将比len [i + 1]大1。否则,如果它们是相同的元素,则len [i]将仅为1。
下面是上述方法的实现:

C++
// C++ program to calculate longest alternating
// sub-array for each index elements
#include 
using namespace std;
 
// Function to calculate alternating sub-
// array for each index of array elements
void alternateSubarray(bool arr[], int n)
{
    int len[n];
 
    // Initialize the base state of len[]
    len[n - 1] = 1;
 
    // Calculating value for each element
    for (int i = n - 2; i >= 0; --i) {
        // If both elements are different
        // then add 1 to next len[i+1]
        if (arr[i] ^ arr[i + 1] == 1)
            len[i] = len[i + 1] + 1;
 
        // else initialize to 1
        else
            len[i] = 1;
    }
 
    // Print lengths of binary subarrays.
    for (int i = 0; i < n; ++i)
        cout << len[i] << " ";
}
 
// Driver program
int main()
{
    bool arr[] = { 1, 0, 1, 0, 0, 1 };
    int n = sizeof(arr) / sizeof(arr[0]);
    alternateSubarray(arr, n);
    return 0;
}


Java
// Java program to calculate longest alternating
// sub-array for each index elements
 
class GFG {
     
// Function to calculate alternating sub-
// array for each index of array elements
static void alternateSubarray(boolean arr[], int n)
{
    int len[] = new int[n];
 
    // Initialize the base state of len[]
    len[n - 1] = 1;
 
    // Calculating value for each element
    for (int i = n - 2; i >= 0; --i) {
         
    // If both elements are different
    // then add 1 to next len[i+1]
    if (arr[i] ^ arr[i + 1] == true)
        len[i] = len[i + 1] + 1;
 
    // else initialize to 1
    else
        len[i] = 1;
    }
 
    // Print lengths of binary subarrays.
    for (int i = 0; i < n; ++i)
    System.out.print(len[i] + " ");
}
 
// Driver code
public static void main(String[] args)
{
    boolean arr[] = {true, false, true, false, false, true};
    int n = arr.length;
    alternateSubarray(arr, n);
}
}
 
// This code is contributed by Anant Agarwal.


Python3
# Python program to calculate
# longest alternating
# sub-array for each index elements
 
# Function to calculate alternating sub-
# array for each index of array elements
def alternateSubarray(arr,n):
 
    len=[]
    for i in range(n+1):
        len.append(0)
         
    # Initialize the base state of len[]
    len[n - 1] = 1
  
    # Calculating value for each element
    for i in range(n - 2,-1,-1):
         
        # If both elements are different
        # then add 1 to next len[i+1]
        if (arr[i] ^ arr[i + 1] == True):
            len[i] = len[i + 1] + 1
  
        # else initialize to 1
        else:
            len[i] = 1
     
  
    # Print lengths of binary subarrays.
    for i in range(n):
        print(len[i] , " ",end="")
  
# Driver code
 
arr = [ True,False, True, False, False, True ]
n = len(arr)
 
alternateSubarray(arr, n)
 
# This code is contributed
# by Anant Agarwal.


C#
// C# program to calculate longest
// alternating sub-array for each
// index elements
using System;
 
class GFG {
     
    // Function to calculate alternating sub-
    // array for each index of array elements
    static void alternateSubarray(bool []arr,
                                        int n)
    {
         
        int []len = new int[n];
     
        // Initialize the base state of len[]
        len[n - 1] = 1;
     
        // Calculating value for each element
        for (int i = n - 2; i >= 0; --i)
        {
             
            // If both elements are different
            // then add 1 to next len[i+1]
            if (arr[i] ^ arr[i + 1] == true)
                len[i] = len[i + 1] + 1;
         
            // else initialize to 1
            else
                len[i] = 1;
        }
     
        // Print lengths of binary subarrays.
        for (int i = 0; i < n; ++i)
            Console.Write(len[i] + " ");
    }
     
    // Driver code
    public static void Main()
    {
        bool []arr = {true, false, true,
                         false, false, true};
        int n = arr.Length;
         
        alternateSubarray(arr, n);
    }
}
 
// This code is contributed by vt_m.


PHP
= 0; --$i)
    {
        // If both elements are different
        // then add 1 to next len[i+1]
        if ($arr[$i] ^ $arr[$i + 1] == 1)
            $len[$i] = $len[$i + 1] + 1;
 
        // else initialize to 1
        else
            $len[$i] = 1;
    }
 
    // Print lengths of binary subarrays.
    for ($i = 0; $i < $n; ++$i)
        echo $len[$i] . " ";
}
 
// Driver Code
$arr = array(1, 0, 1, 0, 0, 1);
$n = sizeof($arr);
alternateSubarray($arr, $n);
 
// This code is contributed by ita_c
?>


Javascript


C++
// C++ program to calculate longest alternating
// sub-array for each index elements
#include 
using namespace std;
 
// Function to calculate alternating sub-array
// for each index of array elements
void alternateSubarray(bool arr[], int n)
{
    // Initialize count variable for storing
    // length of sub-array
    int count = 1;
 
    // Initialize 'prev' variable which
    // indicates the previous element
    // while traversing for index 'i'
    int prev = arr[0];
    for (int i = 1; i < n; ++i) {
 
        // If both elements are same
        // print elements because alternate
        // element is not found for current
        // index
        if ((arr[i] ^ prev) == 0)
        {
            // print count and decrement it.
            while (count)
                cout << count-- << " ";
        }
 
        // Increment count for next element
        ++count;
 
        // Re-initialize previous variable
        prev = arr[i];
    }
 
    // If elements are still available after
    // traversing whole array, print it
    while (count)
        cout << count-- << " ";
}
 
// Driver program
int main()
{
    bool arr[] = { 1, 0, 1, 0, 0, 1 };
    int n = sizeof(arr) / sizeof(arr[0]);
    alternateSubarray(arr, n);
    return 0;
}


Java
// Java program to calculate longest alternating
// sub-array for each index elements
class GFG {
 
// Function to calculate alternating sub-array
// for each index of array elements
    static void alternateSubarray(boolean arr[], int n) {
        // Initialize count variable for storing
        // length of sub-array
        int count = 1;
 
        // Initialize 'prev' variable which
        // indicates the previous element
        // while traversing for index 'i'
        boolean prev = arr[0];
        for (int i = 1; i < n; ++i) {
 
            // If both elements are same
            // print elements because alternate
            // element is not found for current
            // index
            if ((arr[i] ^ prev) == false) {
                // print count and decrement it.
                while (count > 0) {
                    System.out.print(count-- + " ");
                }
            }
 
            // Increment count for next element
            ++count;
 
            // Re-initialize previous variable
            prev = arr[i];
        }
 
        // If elements are still available after
        // traversing whole array, print it
        while (count != 0) {
            System.out.print(count-- + " ");
        }
    }
 
// Driver program
    public static void main(String args[]) {
        boolean arr[] = {true, false, true, false, false, true};
        int n = arr.length;
        alternateSubarray(arr, n);
    }
}
/*This code is contributed by 29AjayKumar*/


Python3
# Python 3 program to calculate longest
# alternating sub-array for each index elements
 
# Function to calculate alternating sub-array
# for each index of array elements
def alternateSubarray(arr, n):
     
    # Initialize count variable for
    # storing length of sub-array
    count = 1
 
    # Initialize 'prev' variable which
    # indicates the previous element
    # while traversing for index 'i'
    prev = arr[0]
    for i in range(1, n):
         
        # If both elements are same, print
        # elements because alternate element
        # is not found for current index
        if ((arr[i] ^ prev) == 0):
             
            # print count and decrement it.
            while (count):
                print(count, end = " ")
                count -= 1
 
        # Increment count for next element
        count += 1
 
        # Re-initialize previous variable
        prev = arr[i]
 
    # If elements are still available after
    # traversing whole array, print it
    while (count):
        print(count, end = " ")
        count -= 1
 
# Driver Code
if __name__ == '__main__':
    arr = [1, 0, 1, 0, 0, 1]
    n = len(arr)
    alternateSubarray(arr, n)
 
# This code is contributed by
# Surendra_Gangwar


C#
// C# program to calculate longest alternating
// sub-array for each index elements
using System;
  
public class Test{
     
// Function to calculate alternating sub-array
// for each index of array elements
    static void alternateSubarray(bool []arr, int n) {
        // Initialize count variable for storing
        // length of sub-array
        int count = 1;
  
        // Initialize 'prev' variable which
        // indicates the previous element
        // while traversing for index 'i'
        bool prev = arr[0];
        for (int i = 1; i < n; ++i) {
  
            // If both elements are same
            // print elements because alternate
            // element is not found for current
            // index
            if ((arr[i] ^ prev) == false) {
                // print count and decrement it.
                while (count > 0) {
                    Console.Write(count-- + " ");
                }
            }
  
            // Increment count for next element
            ++count;
  
            // Re-initialize previous variable
            prev = arr[i];
        }
  
        // If elements are still available after
        // traversing whole array, print it
        while (count != 0) {
            Console.Write(count-- + " ");
        }
    }
  
// Driver program
    public static void Main() {
        bool []arr = {true, false, true, false, false, true};
        int n = arr.Length;
        alternateSubarray(arr, n);
    }
}
/*This code is contributed by 29AjayKumar*/


PHP


输出 :

4 3 2 1 2 1

时间复杂度: O(n)
辅助空间: O(n)
另一种有效的方法是,无需将所有子数组元素存储在len []数组中,我们可以直接打印它,直到找到不匹配(相等的相邻元素)为止。当发现不匹配时,我们将计数从当前值打印到0。

C++

// C++ program to calculate longest alternating
// sub-array for each index elements
#include 
using namespace std;
 
// Function to calculate alternating sub-array
// for each index of array elements
void alternateSubarray(bool arr[], int n)
{
    // Initialize count variable for storing
    // length of sub-array
    int count = 1;
 
    // Initialize 'prev' variable which
    // indicates the previous element
    // while traversing for index 'i'
    int prev = arr[0];
    for (int i = 1; i < n; ++i) {
 
        // If both elements are same
        // print elements because alternate
        // element is not found for current
        // index
        if ((arr[i] ^ prev) == 0)
        {
            // print count and decrement it.
            while (count)
                cout << count-- << " ";
        }
 
        // Increment count for next element
        ++count;
 
        // Re-initialize previous variable
        prev = arr[i];
    }
 
    // If elements are still available after
    // traversing whole array, print it
    while (count)
        cout << count-- << " ";
}
 
// Driver program
int main()
{
    bool arr[] = { 1, 0, 1, 0, 0, 1 };
    int n = sizeof(arr) / sizeof(arr[0]);
    alternateSubarray(arr, n);
    return 0;
}

Java

// Java program to calculate longest alternating
// sub-array for each index elements
class GFG {
 
// Function to calculate alternating sub-array
// for each index of array elements
    static void alternateSubarray(boolean arr[], int n) {
        // Initialize count variable for storing
        // length of sub-array
        int count = 1;
 
        // Initialize 'prev' variable which
        // indicates the previous element
        // while traversing for index 'i'
        boolean prev = arr[0];
        for (int i = 1; i < n; ++i) {
 
            // If both elements are same
            // print elements because alternate
            // element is not found for current
            // index
            if ((arr[i] ^ prev) == false) {
                // print count and decrement it.
                while (count > 0) {
                    System.out.print(count-- + " ");
                }
            }
 
            // Increment count for next element
            ++count;
 
            // Re-initialize previous variable
            prev = arr[i];
        }
 
        // If elements are still available after
        // traversing whole array, print it
        while (count != 0) {
            System.out.print(count-- + " ");
        }
    }
 
// Driver program
    public static void main(String args[]) {
        boolean arr[] = {true, false, true, false, false, true};
        int n = arr.length;
        alternateSubarray(arr, n);
    }
}
/*This code is contributed by 29AjayKumar*/

Python3

# Python 3 program to calculate longest
# alternating sub-array for each index elements
 
# Function to calculate alternating sub-array
# for each index of array elements
def alternateSubarray(arr, n):
     
    # Initialize count variable for
    # storing length of sub-array
    count = 1
 
    # Initialize 'prev' variable which
    # indicates the previous element
    # while traversing for index 'i'
    prev = arr[0]
    for i in range(1, n):
         
        # If both elements are same, print
        # elements because alternate element
        # is not found for current index
        if ((arr[i] ^ prev) == 0):
             
            # print count and decrement it.
            while (count):
                print(count, end = " ")
                count -= 1
 
        # Increment count for next element
        count += 1
 
        # Re-initialize previous variable
        prev = arr[i]
 
    # If elements are still available after
    # traversing whole array, print it
    while (count):
        print(count, end = " ")
        count -= 1
 
# Driver Code
if __name__ == '__main__':
    arr = [1, 0, 1, 0, 0, 1]
    n = len(arr)
    alternateSubarray(arr, n)
 
# This code is contributed by
# Surendra_Gangwar

C#

// C# program to calculate longest alternating
// sub-array for each index elements
using System;
  
public class Test{
     
// Function to calculate alternating sub-array
// for each index of array elements
    static void alternateSubarray(bool []arr, int n) {
        // Initialize count variable for storing
        // length of sub-array
        int count = 1;
  
        // Initialize 'prev' variable which
        // indicates the previous element
        // while traversing for index 'i'
        bool prev = arr[0];
        for (int i = 1; i < n; ++i) {
  
            // If both elements are same
            // print elements because alternate
            // element is not found for current
            // index
            if ((arr[i] ^ prev) == false) {
                // print count and decrement it.
                while (count > 0) {
                    Console.Write(count-- + " ");
                }
            }
  
            // Increment count for next element
            ++count;
  
            // Re-initialize previous variable
            prev = arr[i];
        }
  
        // If elements are still available after
        // traversing whole array, print it
        while (count != 0) {
            Console.Write(count-- + " ");
        }
    }
  
// Driver program
    public static void Main() {
        bool []arr = {true, false, true, false, false, true};
        int n = arr.Length;
        alternateSubarray(arr, n);
    }
}
/*This code is contributed by 29AjayKumar*/

的PHP


输出 :

4 3 2 1 2 1