0
点赞
收藏
分享

微信扫一扫

力扣 剑指 Offer II 011. 0 和 1 个数相同的子数组

转角一扇门 2022-04-05 阅读 82
leetcode

题目来源:https://leetcode-cn.com/problems/A1NYOS/

大致题意:
给一个由 0 和 1 组成的数组,求其中 0 和 1 个数相同的最长子数组

思路

可以将数组中的 0 处理成 -1,然后统计前缀和

  • 这样,若两个位置前缀和相同,那么表示这两个位置之间的子数组的 0 和 1 数量相同

具体实现时

  • 不用处理数组,每次统计前缀和时判断元素值,若为 0 则加上 -1
  • 使用哈希表存下每种前缀和第一次出现的索引,这样每次统计前缀和后,若哈希表已有相同该前缀和,那么取出对应索引即可统计子数组长度。初始时,放入前缀和 0 对应的索引 -1

代码:

class Solution {
    public int findMaxLength(int[] nums) {
        int count = 0;
        Map<Integer, Integer> map = new HashMap<>();
        map.put(count, -1);	// 放入前缀和为 0 对应的索引
        int n = nums.length;
        int ans = 0;
        for (int i = 0; i < n; i++) {
        	// 更新前缀和
            count += nums[i] == 1 ? 1 : -1;
            // 若前缀和出现过,统计最长子数组
            if (map.containsKey(count)) {
                ans = Math.max(i - map.get(count), ans);
            } else {	// 没出现过,放入哈希表
                map.put(count, i);
            }
        }
        return ans;
    }
}
举报

相关推荐

0 条评论