📜  乘积为0的最长子数组

📅  最后修改于: 2021-04-23 18:56:20             🧑  作者: Mango

给定整数元素数组arr [] ,任务是查找乘积为0的最长子数组的长度。
例子:

方法:

  • 如果数组中没有等于0的元素,那么将不会有乘积为0的子数组。
  • 如果数组中至少有一个元素等于0,则乘积为0的最长子数组将是完整数组。

下面是上述方法的实现:

C++
// C++ implementation of the approach
#include 
using namespace std;
 
// Function to return the length of the
// longest sub-array whose product
// of elements is 0
int longestSubArray(int arr[], int n)
{
    bool isZeroPresent = false;
    for (int i = 0; i < n; i++) {
        if (arr[i] == 0) {
            isZeroPresent = true;
            break;
        }
    }
 
    if (isZeroPresent)
        return n;
 
    return 0;
}
 
// Driver code
int main()
{
    int arr[] = { 1, 2, 3, 0, 1, 2, 0 };
    int n = sizeof(arr) / sizeof(arr[0]);
    cout << longestSubArray(arr, n);
 
    return 0;
}


Java
// Java implementation of the approach
class GFG {
 
    // Function to return the length of the
    // longest sub-array whose product
    // of elements is 0
    static int longestSubArray(int arr[], int n)
    {
        boolean isZeroPresent = false;
        for (int i = 0; i < n; i++) {
            if (arr[i] == 0) {
                isZeroPresent = true;
                break;
            }
        }
 
        if (isZeroPresent)
            return n;
 
        return 0;
    }
 
    // Driver code
    public static void main(String args[])
    {
        int arr[] = { 1, 2, 3, 0, 1, 2, 0 };
        int n = arr.length;
        System.out.print(longestSubArray(arr, n));
    }
}


Python3
# Python3 implementation of the approach
 
# Function to return the length of
# the longest sub-array whose product
# of elements is 0
def longestSubArray(arr, n) :
 
    isZeroPresent = False
    for i in range (0 , n) :
        if (arr[i] == 0) :
            isZeroPresent = True
            break
         
    if (isZeroPresent) :
        return n
 
    return 0
 
# Driver code
arr = [ 1, 2, 3, 0, 1, 2, 0 ]
n = len(arr)
print(longestSubArray(arr, n))
 
# This code is contributed by ihritik


C#
// C# implementation of the approach
using System;
class GFG {
 
    // Function to return the length of the
    // longest sub-array whose product
    // of elements is 0
    static int longestSubArray(int[] arr, int n)
    {
        bool isZeroPresent = false;
        for (int i = 0; i < n; i++) {
            if (arr[i] == 0) {
                isZeroPresent = true;
                break;
            }
        }
 
        if (isZeroPresent)
            return n;
 
        return 0;
    }
 
    // Driver code
    public static void Main()
    {
        int[] arr = { 1, 2, 3, 0, 1, 2, 0 };
        int n = arr.Length;
        Console.Write(longestSubArray(arr, n));
    }
}


PHP


Javascript


输出:
7

时间复杂度: O(n)