二进制数组中 1 的最小长度子数组
给定二进制数组。任务是找到最小数量为 1 的子数组的长度。
注意:保证数组中至少存在一个 1。
例子:
Input : arr[] = {1, 1, 0, 0, 1, 1, 1, 0, 1, 1, 1, 1}
Output : 3
Minimum length subarray of 1s is {1, 1}.
Input : arr[] = {0, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1}
Output : 1
简单的解决方案:一个简单的解决方案是考虑每个子数组并计算每个子数组中的 1。最后返回 1s 的最小长度子数组的返回大小。
有效的解决方案:一个有效的解决方案是从左到右遍历数组。如果我们看到 1,我们增加计数。如果我们看到 0,并且到目前为止 1 的计数是正数,则计算计数和结果的最小值并将计数重置为零。
下面是上述方法的实现:
C++
// C++ program to count minimum length
// subarray of 1's in a binary array.
#include
using namespace std;
// Function to count minimum length subarray
// of 1's in binary array arr[0..n-1]
int getMinLength(bool arr[], int n)
{
int count = 0; // initialize count
int result = INT_MAX; // initialize result
for (int i = 0; i < n; i++) {
if (arr[i] == 1) {
count++;
}
else {
if (count != 0)
result = min(result, count);
count = 0;
}
}
return result;
}
// Driver code
int main()
{
bool arr[] = { 1, 1, 0, 0, 1, 1, 1, 0,
1, 1, 1, 1 };
int n = sizeof(arr) / sizeof(arr[0]);
cout << getMinLength(arr, n) << endl;
return 0;
}
Java
// Java program to count minimum length
// subarray of 1's in a binary array.
import java.io.*;
class GFG
{
// Function to count minimum length subarray
// of 1's in binary array arr[0..n-1]
static int getMinLength(double arr[], int n)
{
int count = 0; // initialize count
int result = Integer.MAX_VALUE; // initialize result
for (int i = 0; i < n; i++)
{
if (arr[i] == 1)
{
count++;
}
else
{
if (count != 0)
result = Math.min(result, count);
count = 0;
}
}
return result;
}
// Driver code
public static void main (String[] args)
{
double arr[] = { 1, 1, 0, 0, 1, 1, 1, 0,
1, 1, 1, 1 };
int n = arr.length;
System.out.println (getMinLength(arr, n));
}
}
// This code is contributed by ajit.
Python3
# Python program to count minimum length
# subarray of 1's in a binary array.
import sys
# Function to count minimum length subarray
# of 1's in binary array arr[0..n-1]
def getMinLength(arr, n):
count = 0; # initialize count
result = sys.maxsize ; # initialize result
for i in range(n):
if (arr[i] == 1):
count+=1;
else:
if(count != 0):
result = min(result, count);
count = 0;
return result;
# Driver code
arr = [ 1, 1, 0, 0, 1, 1, 1, 0,
1, 1, 1, 1 ];
n = len(arr);
print(getMinLength(arr, n));
# This code is contributed by Rajput-Ji
C#
// C# program to count minimum length
// subarray of 1's in a binary array.
using System;
class GFG
{
// Function to count minimum length subarray
// of 1's in binary array arr[0..n-1]
static int getMinLength(double []arr, int n)
{
int count = 0; // initialize count
int result = int.MaxValue; // initialize result
for (int i = 0; i < n; i++)
{
if (arr[i] == 1)
{
count++;
}
else
{
if (count != 0)
result = Math.Min(result, count);
count = 0;
}
}
return result;
}
// Driver code
static public void Main ()
{
double []arr = { 1, 1, 0, 0, 1, 1,
1, 0, 1, 1, 1, 1 };
int n = arr.Length;
Console.WriteLine(getMinLength(arr, n));
}
}
// This code is contributed by Tushil..
Javascript
输出:
2
时间复杂度:O(N)
辅助空间:O(1)