题目地址:
https://leetcode.com/problems/read-n-characters-given-read4-ii-call-multiple-times/
给定一个接口int read4(char * buf)
可以每次从文件中读取
4
4
4个字符,返回值是实际读取的字符数(有可能文件剩下的字符数不够,从而返回小于
4
4
4的数字)。要求通过这个接口,实现从文件读取
n
n
n个字符的函数,返回值也是实际读取的字符数。这个函数会调用多次。
参考https://blog.csdn.net/qq_46105170/article/details/109482719。代码如下:
class Solution {
public:
char buf4[4];
int head, tail;
Solution() { head = tail = 0; }
/**
* @param buf Destination buffer
* @param n Number of characters to read
* @return The number of actual characters read
*/
int read(char *buf, int n) {
int res = 0;
while (res < n) {
if (head == tail) {
head = 0;
tail = read4(buf4);
}
if (!tail) break;
while (res < n && head < tail) buf[res++] = buf4[head++];
}
return res;
}
};
时间复杂度 O ( n ) O(n) O(n),空间 O ( 1 ) O(1) O(1)。