525. Contiguous Array

网友投稿 572 2022-09-06

525. Contiguous Array

525. Contiguous Array

Given a binary array, find the maximum length of a contiguous subarray with equal number of 0 and 1.

Example 1:

Input: [0,1]Output: 2Explanation: [0, 1] is the longest contiguous subarray with equal number of 0 and 1.

Example 2:

Input: [0,1,0]Output: 2Explanation: [0, 1] (or [1, 0]) is a longest contiguous subarray with equal number of 0 and 1.

Note: The length of the given binary array will not exceed 50,000.

思路: 本题和maximun size subarray sum equal k比较类似,这里有一个把0转换成-1来进行计算的过程,然后存储一个hashmap用来存放sum,如果接下来的sum在hashmap里面出现过,则说明hashmap里面出现的那个值的索引的开始(不包括索引),到目前的索引的和为0。

class Solution public int findMaxLength(int[] nums) { Map map = new HashMap(); map.put(0, -1); int sum = 0; int max = 0; for(int i = 0; i < nums.length; i++){ if(nums[i] == 0) nums[i] = -1; sum += nums[i]; if(map.containsKey(sum)){ max = Math.max(max, i - map.get(sum)); }else{ map.put(sum, i); } } return

版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们jiasou666@gmail.com 处理,核实后本网站将在24小时内删除侵权内容。

上一篇:133. Clone Graph
下一篇:创建数据库(创建数据库的三种方法)
相关文章

 发表评论

暂时没有评论,来抢沙发吧~