하단 Title 클릭 시 해당 문제 페이지로 이동합니다.
Given a binary array nums, return the maximum length of a contiguous subarray with an equal number of 0 and 1.
1 <= nums.length <= 10^5nums[i] is either 0 or 1.예시 1
Input: nums = [0,1]
Output: 2
Explanation: [0, 1] is the longest contiguous subarray with an equal number of 0 and 1.
예시 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.
total = 0 에서 값이0이면 -1, 1이면 +1을 더해가며 total = 0 이 되는 경우는 0과 1의 갯수가 같다는 말.index = i, total = n 일 때, 이전에 total값 중 n이 나온 경우가 있다면 (index = m), subarray(m, n)은 total = 0 일 것이다. import java.util.HashMap;
import java.util.Map;
class Solution {
public int findMaxLength(int[] nums) {
int total = 0, result = 0;
Map<Integer, Integer> map = new HashMap<>();
for (int index = 0, length = nums.length; index < length; index++) {
int number = nums[index] == 1 ? 1 : -1;
total += number;
if (total == 0) {
result = Math.max(result, index + 1);
}
if (map.containsKey(total)) {
result = Math.max(result, index - map.get(total));
} else {
map.put(total, index);
}
}
return result;
}
}