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

📅  最后修改于: 2021-09-22 10:35:47             🧑  作者: Mango

给定一个只包含 0 和 1 的数组。对于每个索引 ‘ i ‘(0 索引),找到从 ‘ i ‘ 到 ‘ j ‘ 的最长交替子数组的长度,即a i..j for i <= j < n 。交替子阵列意味着任何两个相邻的元素应该不同。

例子:

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


Javascript


输出 :

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*/

蟒蛇3

# 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


Javascript


输出 :

4 3 2 1 2 1

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

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