-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path525_Contiguous_Array
31 lines (30 loc) · 952 Bytes
/
525_Contiguous_Array
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
class Solution {
public:
int findMaxLength(vector<int>& nums) {
int current_sum = 0, result = 0;
for (int start = 0; start < nums.size(); ++start){
current_sum = 0;
for (int end = start; end < nums.size(); ++end){
current_sum += nums[end] * 2;
if (end - start + 1 == current_sum) result = max(current_sum, result);
}
}
return result;
}
};
class Solution {
public:
int findMaxLength(vector<int>& nums) {
int count = 0, maxlength = 0;
unordered_map<int, int> hashmap;
hashmap.insert(make_pair(0, -1));
for (int i = 0; i < nums.size(); ++i){
count += (nums[i] == 1) ? 1 : -1;
if (hashmap.count(count) == 0)
hashmap.insert(make_pair(count, i));
else
maxlength = max(maxlength, i - hashmap[count]);
}
return maxlength;
}
};