给定一个二进制数组, 找到含有相同数量的 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;
}