LeetCode 525. Contiguous Array【前缀和/哈希表】

博客围绕给定的二进制数组,要找到含相同数量0和1的最长连续子数组长度。将数组中所有0转换为 -1,把问题等价为求元素之和等于0的子数组,采用前缀和加哈希表的解法,并提及运行效率。

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

Example 1:

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

Example 2:

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

Constraints:

  • 1 <= nums.length <= 105
  • nums[i] is either 0 or 1.

题意:给定一个二进制数组, 找到含有相同数量的 01 的最长连续子数组(的长度)。


解法 前缀和+哈希表

这一题,我们将 nums[] 中所有 0 转换为 -1 ,所以求含有相同数量的 01 的连续子数组,等价于求元素之和等于 0 的子数组,比较这些子数组的长度并取最大值作为题解。

class Solution {
public:
    int findMaxLength(vector<int>& nums) {
        int n = nums.size(), sum = 0, ans = 0;
        unordered_map<int, int> rec; //rec[k]=i表示元素和为k的子数组,最左边的坐标是i
        rec[0] = 0;
        for (int i = 0; i < n; ++i) {
            sum += !nums[i] ? -1 : nums[i];
            if (rec.find(sum) == rec.end()) rec[sum] = i + 1;
            else ans = max(ans, i + 1 - rec[sum]);
        }
        return ans;
    }
};

运行效率如下:

执行用时:140 ms, 在所有 C++ 提交中击败了73.21% 的用户
内存消耗:81.8 MB, 在所有 C++ 提交中击败了22.32% 的用户
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

memcpy0

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值