LeetCode 30天挑战 Day-13

LeetCode 30 days Challenge - Day 13

本系列将对LeetCode新推出的30天算法挑战进行总结记录,旨在记录学习成果、方便未来查阅,同时望为广大网友提供帮助。


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: 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.


Solution

题目要求分析:给定一个只包含0或1的数组,求满足条件(子数组中0和1数量相等)的最长连续子数组的长度。

解法:

本题关键是遍历数组,确保不漏掉符合条件的子数组,并更新最大长度。

这里为了减少空间复杂度,使用哈希结构建立count(初始为0,遇0减1,遇1加1)到pos(count第一次出现的位置)的映射:

  1. 初始化res为最大长度,count为当前1和0的个数差,负数表示0比1多。
  2. 建立映射,初始化m[0] = -1的意义是:无论第一个元素是0还是1,count都将变为非0,因此,count=0首次出现的位置实际上是-1处(不存在,只是虚拟出一个位置,以保证当最长子数组包含第一个元素的时候,能正确计算长度)。
  3. 在遍历过程中:
    1. m.find(count) == m.end()即新的count值首次出现,记录其位置。
    2. 反之,更新res为较大值。

以下提供参考图片供读者理解:


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

传送门:Contiguous Array

2020/4 Karl

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值