📌  相关文章
📜  1s 计数比 0s 多 1 的最长子数组

📅  最后修改于: 2021-10-28 01:33:31             🧑  作者: Mango

给定一个大小为n的数组,其中只包含 0 和 1。问题是找到最长的子数组的长度,其中 1 的计数比 0 的计数多一。
例子:

Input : arr = {0, 1, 1, 0, 0, 1}
Output : 5
From index 1 to 5.

Input : arr[] = {1, 0, 0, 1, 0}
Output : 1

方法:以下是步骤:

  1. 将数组中的所有 0 视为“-1”。
  2. 初始化sum = 0 和maxLen = 0。
  3. 创建一个具有(sum, index)元组的哈希表。
  4. 对于 i = 0 到 n-1,执行以下步骤:
    1. 如果 arr[i] 是 ‘0’ 累积 ‘-1’ 到sum否则累积 ‘1’ 到sum
    2. 如果 sum == 1,则更新maxLen = i+1。
    3. 否则检查总和是否存在于哈希表中。如果不存在,则将其作为(sum, i)对添加到哈希表中。
    4. 检查(sum-1)是否存在于哈希表中。如果存在,则从哈希表中获取(sum-1)索引作为index 。现在检查 maxLen 是否小于 (i-index),然后更新maxLen = (i-index)。
  5. 返回 maxLen。
C++
// C++ implementation to find the length of
// longest subarray having count of 1's one
// more than count of 0's
#include 
using namespace std;
 
// function to find the length of longest
// subarray having count of 1's one more
// than count of 0's
int lenOfLongSubarr(int arr[], int n)
{
    // unordered_map 'um' implemented as
    // hash table
    unordered_map um;
    int sum = 0, maxLen = 0;
 
    // traverse the given array
    for (int i = 0; i < n; i++) {
 
        // consider '0' as '-1'
        sum += arr[i] == 0 ? -1 : 1;
 
        // when subarray starts form index '0'
        if (sum == 1)
            maxLen = i + 1;
 
        // make an entry for 'sum' if it is
        // not present in 'um'
        else if (um.find(sum) == um.end())
            um[sum] = i;
 
        // check if 'sum-1' is present in 'um'
        // or not
        if (um.find(sum - 1) != um.end()) {
 
            // update maxLength
            if (maxLen < (i - um[sum - 1]))
                maxLen = i - um[sum - 1];
        }
    }
 
    // required maximum length
    return maxLen;
}
 
// Driver program to test above
int main()
{
    int arr[] = { 0, 1, 1, 0, 0, 1 };
    int n = sizeof(arr) / sizeof(arr[0]);
    cout << "Length = "
         << lenOfLongSubarr(arr, n);
    return 0;
}


Java
// Java implementation to find the length of
// longest subarray having count of 1's one
// more than count of 0's
import java.util.*;
 
class GFG
{
 
// function to find the length of longest
// subarray having count of 1's one more
// than count of 0's
static int lenOfLongSubarr(int arr[], int n)
{
    // unordered_map 'um' implemented as
    // hash table
    HashMap um = new HashMap();
    int sum = 0, maxLen = 0;
 
    // traverse the given array
    for (int i = 0; i < n; i++)
    {
 
        // consider '0' as '-1'
        sum += arr[i] == 0 ? -1 : 1;
 
        // when subarray starts form index '0'
        if (sum == 1)
            maxLen = i + 1;
 
        // make an entry for 'sum' if it is
        // not present in 'um'
        else if (!um.containsKey(sum))
            um. put(sum, i);
 
        // check if 'sum-1' is present in 'um'
        // or not
        if (um.containsKey(sum - 1))
        {
 
            // update maxLength
            if (maxLen < (i - um.get(sum - 1)))
                maxLen = i - um.get(sum - 1);
        }
    }
 
    // required maximum length
    return maxLen;
}
 
// Driver Code
public static void main(String[] args)
{
    int arr[] = { 0, 1, 1, 0, 0, 1 };
    int n = arr.length;
    System.out.println("Length = " +
               lenOfLongSubarr(arr, n));
}
}
 
// This code is contributed by Princi Singh


Python3
# Python 3 implementation to find the length of
# longest subarray having count of 1's one
# more than count of 0's
 
# function to find the length of longest
# subarray having count of 1's one more
# than count of 0's
def lenOfLongSubarr(arr, n):
     
    # unordered_map 'um' implemented as
    # hash table
    um = {i:0 for i in range(10)}
    sum = 0
    maxLen = 0
 
    # traverse the given array
    for i in range(n):
         
        # consider '0' as '-1'
        if arr[i] == 0:
            sum += -1
        else:
            sum += 1
 
        # when subarray starts form index '0'
        if (sum == 1):
            maxLen = i + 1
 
        # make an entry for 'sum' if it is
        # not present in 'um'
        elif (sum not in um):
            um[sum] = i
 
        # check if 'sum-1' is present in 'um'
        # or not
        if ((sum - 1) in um):
            # update maxLength
            if (maxLen < (i - um[sum - 1])):
                maxLen = i - um[sum - 1]
 
    # required maximum length
    return maxLen
 
# Driver code
if __name__ == '__main__':
    arr = [0, 1, 1, 0, 0, 1]
    n = len(arr)
    print("Length =",lenOfLongSubarr(arr, n))
     
# This code is contributed by
# Surendra_Gangwar


C#
// C# implementation to find the length of
// longest subarray having count of 1's one
// more than count of 0's
using System;
using System.Collections.Generic;
     
class GFG
{
 
// function to find the length of longest
// subarray having count of 1's one more
// than count of 0's
static int lenOfLongSubarr(int []arr, int n)
{
    // unordered_map 'um' implemented as
    // hash table
    Dictionary um = new Dictionary();
    int sum = 0, maxLen = 0;
 
    // traverse the given array
    for (int i = 0; i < n; i++)
    {
 
        // consider '0' as '-1'
        sum += arr[i] == 0 ? -1 : 1;
 
        // when subarray starts form index '0'
        if (sum == 1)
            maxLen = i + 1;
 
        // make an entry for 'sum' if it is
        // not present in 'um'
        else if (!um.ContainsKey(sum))
            um.Add(sum, i);
 
        // check if 'sum-1' is present in 'um'
        // or not
        if (um.ContainsKey(sum - 1))
        {
 
            // update maxLength
            if (maxLen < (i - um[sum - 1]))
                maxLen = i - um[sum - 1];
        }
    }
 
    // required maximum length
    return maxLen;
}
 
// Driver Code
public static void Main(String[] args)
{
    int []arr = { 0, 1, 1, 0, 0, 1 };
    int n = arr.Length;
    Console.WriteLine("Length = " +
            lenOfLongSubarr(arr, n));
}
}
 
// This code is contributed by Rajput-Ji


Javascript


输出:

Length = 5

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