【Leetcode】525. Contiguous Array

题目地址:

https://leetcode.com/problems/contiguous-array/

给定一个长 n n n 0 − 1 0-1 01数组 A A A,求其最长的 0 0 0的个数等于 1 1 1的个数的子数组的长度。

考虑将每个 0 0 0变为 − 1 -1 1,那么本题即为求最长的和为 0 0 0的子数组长度,可以用前缀和的思想来做。开一个哈希表,key是前缀和,value是该前缀和对应的最左边的下标。遍历 A A A,维护一个前缀和变量,如果哈希表里存在这个前缀和作为key,那么就找到了以当前位置为右端点的最长的和为 0 0 0的子数组的左端点减 1 1 1的位置,那么子数组的长度就得出来了。代码如下:

import java.util.HashMap;
import java.util.Map;

public class Solution {
    public int findMaxLength(int[] nums) {
        Map<Integer, Integer> map = new HashMap<>();
        map.put(0, -1);
        
        int res = 0;
        for (int i = 0, sum = 0; i < nums.length; i++) {
            sum += nums[i] * 2 - 1;
            if (map.containsKey(sum)) {
                res = Math.max(res, i - map.get(sum));
            } else {
                map.put(sum, i);
            }
        }
        
        return res;
    }
}

时空复杂度 O ( n ) O(n) O(n)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值