加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 大数据 > 正文

994.Contiguous Array 邻近数组

发布时间:2020-12-14 04:29:24 所属栏目:大数据 来源:网络整理
导读:描述 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: 2 Explanation: [0,1] is the longest contiguous subarray with equal number of 0 and 1. Example 2:

描述

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: 2
Explanation: [0,1] is the longest contiguous subarray with equal number of 0 and 1.

Example 2:

Input: [0,1,0]
Output: 2
Explanation: [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个数相等的子数组的长度。
这里用到一个sum,遇到1就加1,遇到0就减1,这样就会得到每个角标下的sum。
哈希表建立sum值和角标之间的映射。
遍历num成员计算sum值,如果哈希表中存在该sum值,就用当前角标减去哈希表中sum对应的角标,就会得到中间子数组长度,比较更新res。如果哈希表中不存在则添加该sum值和对应的角标。

class Solution {
public:
    int findMaxLength(vector<int>& nums) {
        int res = 0,n = nums.size(),sum = 0;
        unordered_map<int,int> m{{0,-1}};
        for (int i = 0; i < n; ++i) {
            sum += (nums[i] == 1) ? 1 : -1;
            if (m.count(sum)) {
                res = max(res,i - m[sum]);
            } else {
                m[sum] = i;
            }
        }
        return res;
    }
};

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读