leetcode题解-525. Contiguous Array

本文介绍了一种解决寻找二进制数组中最长连续子数组的问题的方法,该子数组包含相等数量的0和1。提供了两种高效算法,分别击败了65%和95.7%的用户。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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

这个题目好像是新出的,其实我一看到这个题的时候思路有点乱,一直没有理清楚0和1应该怎么去处理他们的关系才能保证得到正确的答案。然后去看了一下discuss,下面记录一下。
方法一,使用一个数组diff[]来记录当前位置之前所有出现的1减去所有的0。然后使用map来保存diff[i]与其索引i。这样的话每当diff[j] == diff[i]时,就意味着i到j之间是一个满足条件的子数组。这种方法击败了65%的用户。代码入下:

    public int findMaxLength(int[] nums) {
        int res = 0;
        Map<Integer, Integer> map = new HashMap<>();
        int n = nums.length;
        int [] diff = new int[n+1];
        map.put(0, 0);

        for(int i=1; i<=n; i++){
            diff[i] = diff[i-1] + (nums[i-1] == 0 ? -1 : 1);
            if(!map.containsKey(diff[i]))
                map.put(diff[i], i);
            else
                res = Math.max(res, i-map.get(diff[i]));
        }
        return res;
    }

方法二,思路类似,也是使用map来记录之前遍历过的数组信息,这种方法击败了95.7%的用户。代码入下:

    public int findMaxLength2(int[] nums) {
        Map<Integer, Integer> map = new HashMap<Integer, Integer>() {{put(0,0);}};
        int maxLength = 0, runningSum = 0;
        for (int i=0;i<nums.length;i++) {
            runningSum += nums[i];
            Integer prev = map.get(2*runningSum-i-1);
            if (prev != null) maxLength = Math.max(maxLength, i+1-prev);
            else map.put(2*runningSum-i-1, i+1);
        }
        return maxLength;
    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值