-
Notifications
You must be signed in to change notification settings - Fork 31
/
Copy path525. Contiguous Array.c
97 lines (81 loc) · 1.98 KB
/
525. Contiguous Array.c
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
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
/*
525. Contiguous Array
Given a binary array, find the maximum length of a contiguous subarray with equal number of 0 and 1.
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.
Note:
The length of the given binary array will not exceed 50,000.
*/
typedef struct elem_s {
int n;
int idx;
struct elem_s *shadow;
} elem_t;
#define SZ 10240
void free_set(elem_t **set, int sz) {
int i;
elem_t *e, *s;
for (i = 0; i < sz; i ++) {
e = set[i];
while (e) {
s = e->shadow;
free(e);
e = s;
}
}
}
void put(elem_t **set, int n, int idx) {
int k = n; //(n >= 0) ? n : -n;
elem_t *e = malloc(sizeof(elem_t));
e->n = n;
e->idx = idx;
e->shadow = set[k % SZ];
set[k % SZ] = e;
}
elem_t *lookup(elem_t **set, int n) {
int k = n; //(n >= 0) ? n : -n;
elem_t *e = set[k % SZ];
while (e && e->n != n) e = e->shadow;
return e;
}
int findMaxLength(int* nums, int numsSize) {
int n[2] = { 0 };
int i, d = 0;
elem_t *buff[SZ * 2] = { 0 };
elem_t *e, *set = &buff[SZ];
if (!numsSize) return 0;
put(set, 0, -1);
for (i = 0; i < numsSize; i ++) {
n[nums[i]] ++;
e = lookup(set, n[0] - n[1]);
if (!e) {
put(set, n[0] - n[1], i);
} else if (d < i - e->idx) {
d = i - e->idx;
}
}
free_set(buff, sizeof(buff)/sizeof(buff[0]));
return d;
}
/*
Difficulty:Medium
Total Accepted:12.3K
Total Submissions:31.5K
Companies Facebook
Related Topics Hash Table
Similar Questions
Maximum Size Subarray Sum Equals k
*/