contiguous-array
Problem
Problem Description
Solution
Continuous subarray with equal 0 and 1, here counting 0s and 1s.
if 0s, count + 1,
if 1s, count - 1. if encounter count = 0, then 0s and 1s are equal. then how to find the longest contiguous subarray? using map to keep track of count as key and index as value, if we encounter count = 0, keep the first count = 0 index, len = current index - map.get(count), max = max(max, len). and if encounter the same count, the meaning between previous same count and current count has equal number of 0s and 1s.
init HashMap map, and count = 0, map.put(0, -1), why put(0, -1)? because for index 0, we need to init, otherwise cannot count index 0 number. for example, [0,1] max = 2.
if 0s, count + 1, if 1s, count - 1
check whether map already contains count?
if not, put current count and current index into map. map.put(count, idx)
if yes, then check current length of equal number of 0s and 1s, len = idx - map.get(count). and compare max and len.
max = max(max, len)
continue count 0s and 1s, until the end of array
return max
For example:
Complexity Analysis
Time Complexity: O(N)
Space Complexity: O(N)
N - the length of array nums.
Code
Java code
Last updated