Contiguous Array – LeetCode Solution Java , Python 3, Python 2 , C , C++, Best and Optimal Solutions , All you need.
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 either0
or1
.
C++ Contiguous Array LeetCode Solution
class Solution {
public:
int findMaxLength(vector<int>& nums) {
int count = 0;
for (int i = 0; i < nums.size(); i++) {
int zeros = 0, ones = 0;
for (int j = i; j < nums.size(); j++) {
if (nums[j] == 0) {
zeros++;
} else {
ones++;
}
if (zeros == ones) {
count = max(count, j - i + 1);
}
}
}
return count;
}
};
Java Contiguous Array LeetCode Solution
class Solution {
public int findMaxLength(int[] nums) {
int count = 0;
for (int i = 0; i < nums.length; i++) {
int zeros = 0, ones = 0;
for (int j = i; j < nums.length; j++) {
if (nums[j] == 0) {
zeros++;
} else {
ones++;
}
if (zeros == ones) {
count = Math.max(count, j - i + 1);
}
}
}
return count;
}
}
Python 3 Contiguous Array LeetCode Solution
class Solution(object):
def findMaxLength(self, nums):
count = 0
max_length=0
table = {0: 0}
for index, num in enumerate(nums, 1):
if num == 0:
count -= 1
else:
count += 1
if count in table:
max_length = max(max_length, index - table[count])
else:
table[count] = index
return max_length
Array-1180
String-562
Hash Table-412
Dynamic Programming-390
Math-368
Sorting-264
Greedy-257
Depth-First Search-256
Database-215
Breadth-First Search-200
Tree-195
Binary Search-191
Matrix-176
Binary Tree-160
Two Pointers-151
Bit Manipulation-140
Stack-133
Heap (Priority Queue)-117
Design-116
Graph-108
Simulation-103
Prefix Sum-96
Backtracking-92
Counting-86
Sliding Window-73
Linked List-69
Union Find-66
Ordered Set-48
Monotonic Stack-47
Recursion-43
Trie-41
Binary Search Tree-40
Divide and Conquer-40
Enumeration-39
Bitmask-37
Queue-33
Memoization-32
Topological Sort-31
Geometry-30
Segment Tree-27
Game Theory-24
Hash Function-24
Binary Indexed Tree-21
Interactive-18
Data Stream-17
String Matching-17
Rolling Hash-17
Shortest Path-16
Number Theory-16
Combinatorics-15
Randomized-12
Monotonic Queue-9
Iterator-9
Merge Sort-9
Concurrency-9
Doubly-Linked List-8
Brainteaser-8
Probability and Statistics-7
Quickselect-7
Bucket Sort-6
Suffix Array-6
Minimum Spanning Tree-5
Counting Sort-5
Shell-4
Line Sweep-4
Reservoir Sampling-4
Eulerian Circuit-3
Radix Sort-3
Strongly Connected Componen-t2
Rejection Sampling-2
Biconnected Component-1