-
Notifications
You must be signed in to change notification settings - Fork 3
/
158.cpp
45 lines (44 loc) · 1.05 KB
/
158.cpp
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
/**
* The read4 API is defined in the parent class Reader4.
* int read4(char *buf4);
*/
class Solution {
public:
/**
* @param buf Destination buffer
* @param n Number of characters to read
* @return The number of actual characters read
*/
int currIdx = 0;
char buf4[4];
int left = 0;
queue<char> q;
int read(char *buf, int n) {
int res = 0;
while (left > 0 && n > 0) {
buf[res] = q.front();
q.pop();
left--;
n--;
res++;
currIdx++;
}
while (n > 0) {
int load = read4(buf4);
int maxVal = min(n, load);
if (maxVal == 0) return res;
for (int i = 0; i < maxVal; ++i) {
buf[res] = buf4[i];
currIdx++;
res++;
}
n -= maxVal;
while (load > maxVal) {
q.push(buf4[maxVal]);
left++;
maxVal++;
}
}
return res;
}
};