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

阅读: 评论:0

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

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]);elsedict[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; }

 

本文发布于:2024-02-02 09:50:17,感谢您对本站的认可!

本文链接:https://www.4u4v.net/it/170683861643000.html

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。

标签:数组   leetcode   哈希
留言与评论(共有 0 条评论)
   
验证码:

Copyright ©2019-2022 Comsenz Inc.Powered by ©

网站地图1 网站地图2 网站地图3 网站地图4 网站地图5 网站地图6 网站地图7 网站地图8 网站地图9 网站地图10 网站地图11 网站地图12 网站地图13 网站地图14 网站地图15 网站地图16 网站地图17 网站地图18 网站地图19 网站地图20 网站地图21 网站地图22/a> 网站地图23