g0501_0600.s0525_contiguous_array.Solution Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of leetcode-in-java21 Show documentation
Show all versions of leetcode-in-java21 Show documentation
Java-based LeetCode algorithm problem solutions, regularly updated
package g0501_0600.s0525_contiguous_array;
// #Medium #Array #Hash_Table #Prefix_Sum #2022_07_28_Time_31_ms_(80.05%)_Space_77.6_MB_(61.34%)
import java.util.HashMap;
/**
* 525 - Contiguous Array\.
*
* Medium
*
* Given a binary array `nums`, return _the maximum length of a contiguous subarray with an equal number of_ `0` _and_ `1`.
*
* **Example 1:**
*
* **Input:** nums = [0,1]
*
* **Output:** 2
*
* **Explanation:** [0, 1] is the longest contiguous subarray with an equal number of 0 and 1.
*
* **Example 2:**
*
* **Input:** nums = [0,1,0]
*
* **Output:** 2
*
* **Explanation:** [0, 1] (or [1, 0]) is a longest contiguous subarray with equal number of 0 and 1.
*
* **Constraints:**
*
* * 1 <= nums.length <= 105
* * `nums[i]` is either `0` or `1`.
**/
public class Solution {
public int findMaxLength(int[] nums) {
for (int i = 0; i < nums.length; i++) {
if (nums[i] == 0) {
nums[i] = -1;
}
}
HashMap map = new HashMap<>();
map.put(0, -1);
int ps = 0;
int len = 0;
for (int i = 0; i < nums.length; i++) {
ps += nums[i];
if (!map.containsKey(ps)) {
map.put(ps, i);
} else {
len = Math.max(len, i - map.get(ps));
}
}
return len;
}
}
© 2015 - 2025 Weber Informatics LLC | Privacy Policy