---
# System prepended metadata

title: 0525. Contiguous Array
tags: [Leetcode, HashMap, Prefix Sum, Medium]

---

# 0525. Contiguous Array
###### tags: `Leetcode` `Medium` `HashMap` `Prefix Sum`
Link: https://leetcode.com/problems/contiguous-array/
## 思路
用-1取代0，这样如果一个区间0和1的数目相等，这个区间的和就为0，所以用hashmap记录曾经出现过的sum，如果后面出现一样的sum，就代表可以更新答案
## Code
```java=
class Solution {
    public int findMaxLength(int[] nums) {
        for(int i=0; i<nums.length; i++){
            if(nums[i]==0) nums[i]=-1; 
        }
        Map<Integer, Integer> map = new HashMap<>();
        map.put(0,-1);
        int sum = 0, ans = 0;
        for(int i=0; i<nums.length; i++){
            sum += nums[i];
            if(!map.containsKey(sum)){
                map.put(sum, i);
            }
            else{
                ans = Math.max(ans, i-map.get(sum));
            }
        }
        return ans;
        
    }
}
```