c# leetcode 525. 连续数组(哈希)

给定一个二进制数组, 找到含有相同数量的 0 和 1 的最长连续子数组(的长度)。

示例 1:

输入: [0,1]
输出: 2
说明: [0, 1] 是具有相同数量0和1的最长连续子数组。

示例 2:

输入: [0,1,0]
输出: 2
说明: [0, 1] (或 [1, 0]) 是具有相同数量0和1的最长连续子数组。

注意: 给定的二进制数组的长度不会超过50000。

~~

public int FindMaxLength(int[] nums)
        {
            var count = 0;
            var dict = new Dictionary<int, int>();
            dict[0] = -1;
            var maxL = 0;
            for (int i = 0; i < nums.Length; i++)
            {
                count += (nums[i] == 0 ? -1 : 1);
                if (dict.ContainsKey(count))
                {
                    maxL = Math.Max(maxL, i - dict[count]);
                }
                else
                {
                    dict[count]= i;
                }
            }
            return maxL;
        }

一:用暴力破解

public class Solution {
    public int FindMaxLength(int[] nums) {
int maxLin = 0;
            for (int start = 0; start < nums.Length; start++)
            {
                int zeroes = 0, one = 0;
                for (int end = start; end < nums.Length; end++)
                {
                    if (nums[end]==0)
                    {
                        zeroes++;
                    }
                    else
                    {
                        one++;
                    }
                    if (zeroes==one)
                    {
                        maxLin = Math.Max(maxLin, end - start + 1);
                    }
                }
            }
            return maxLin;
    }
}

暴力破解的思维还是要有的,这是最后准确率的底线, 尽管经常会超时。

经典哈希算法:

public static int FindMaxLength(int[] nums)
        {
            Dictionary<int, int> dict = new Dictionary<int, int>();
            int count = 0;
            int maxLength = 0;
            for (int i = 0; i < nums.Length; i++)
            {
                if (nums[i] == 1) count++;
                if (nums[i] == 0) count--;

                if (dict.ContainsKey(count))
                    maxLength = Math.Max(maxLength, i - dict[count]);
                else
                    dict[count] = i;

                if (count == 0)    //If count ever becomes 0 that means from start till current index i, we have max contiguous array. 
                    maxLength = i + 1;
            }
            return maxLength; 
        }

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值