Read N Characters Given Read4 II - Call multiple times
https://leetcode.com/problems/read-n-characters-given-read4-ii-call-multiple-times/description/ https://www.lintcode.com/problem/read-n-characters-given-read4-ii-call-multiple-times/description
Thoughts
Code
// Forward declaration of the read4 API.
int read4(char *buf);
class Solution {
public:
/**
* @param buf destination buffer
* @param n maximum number of characters to read
* @return the number of characters read
*/
char inbuf[4];
int read_pos = 0, write_pos = 0;
int read(char *buf, int n) {
for (int i = 0; i < n; ++i) {
if (read_pos == write_pos) {
write_pos = read4(inbuf);
read_pos = 0;
if (write_pos == 0) return i;
}
buf[i] = inbuf[read_pos++];
}
return n;
}
};Analysis
Last updated