Given a binary array, find the maximum length of a contiguous subarray with equal number of 0 and 1.
Note: The length of the given binary array will not exceed 50,000.
給予一個二元陣列,找到最大長度的子陣列,其包含的0和1數量相同。
提示:給予的二元陣列最長不超過50000。
Example 1:
Input: [0,1]
Output: 2
Explanation: [0, 1] is the longest contiguous subarray with equal number of 0 and 1.
Example 2:
Input: [0,1,0]
Output: 2
Explanation: [0, 1] (or [1, 0]) is a longest contiguous subarray with equal number of 0 and 1.
0
就減一,遇到1
就加一。
class Solution {
public:
int findMaxLength(vector<int>& nums) {
int ans = 0;
for(int j = 0; j < nums.size(); j++)
{
int sum = 0;
int count = 0;
for(int i = j; i < nums.size(); i++)
{
if(nums[i] == 0)
sum--;
else if(nums[i] == 1)
sum++;
count++;
if(sum == 0)
ans = ans < count ? count : ans;
}
}
return ans;
}
};
O(n^2)
,吃到TLE。0
和1
是一樣多的!O(n)
new
新增陣列取代掉vector
等結構,以縮短allocate的時間。
class Solution {
public:
int findMaxLength(vector<int>& nums) {
int sum = 0;
int ans = 0;
unordered_map<int,int> hash;
hash[0] = -1;
int s = nums.size();
for(int i = 0; i < s; i++)
{
if(nums[i] == 0)
sum--;
else if(nums[i] == 1)
sum++;
nums[i] = sum;
if(hash.count(sum))
ans = max(ans, i - hash[sum]);
else
hash[sum] = i;
}
return ans;
}
};
LeetCode
C++