LeetCode 525: Continuous Array

Posted keepshuatishuati

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了LeetCode 525: Continuous Array相关的知识,希望对你有一定的参考价值。

Note: 1. Remember to intial (0, -1) since this kind of problems need a starting point.

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

 

以上是关于LeetCode 525: Continuous Array的主要内容,如果未能解决你的问题,请参考以下文章

LeetCode:Continuous Subarray Sum

leetcode: Continuous Subarray Sum

581. Shortest Unsorted Continuous Subarray (LeetCode)

[LeetCode] Longest Continuous Increasing Subsequence 最长连续递增序列

leetcode 523. Continuous Subarray Sum

Leetcode 523: Continuous Subarray Sum