[leetcode] 525. Contiguous Array

网友投稿 559 2022-11-08

[leetcode] 525. Contiguous Array

[leetcode] 525. Contiguous Array

Description

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.

分析

题目的意思是:给你一个只有0或者1的数组,然后截取子数组使得0的数量跟1的数量是一样多的,求这种子数组的个数。

需要用到一个trick,遇到1就加1,遇到0,就减1,这样如果某个子数组和为0,就说明0和1的个数相等。我们用一个哈希表建立子数组之和跟结尾位置的坐标之间的映射。如果某个子数组之和在哈希表里存在了,说明当前子数组减去哈希表中存的那个子数字,得到的结果是中间一段子数组之和,必然为0,说明0和1的个数相等,我们更新结果res

代码

class Solution {public: int findMaxLength(vector& nums) { int n=nums.size(); int res=0; unordered_map m{{0,-1}}; int sum=0; for(int i=0;i

参考文献

​​[LeetCode] Contiguous Array 邻近数组​​

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

上一篇:[leetcode] 554. Brick Wall
下一篇:[leetcode] 649. Dota2 Senate
相关文章

 发表评论

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