题目地址:
https://leetcode.com/problems/read-n-characters-given-read4/
给定一个API,函数是这样的:int read4(char* buf4)
,其能在某个文件里顺次读最多
4
4
4个字符(每次读取之后指针都会后移到下一次应该开始读取的位置),如果还没读到文件尾就已经读了
4
4
4个字符了,则就读到文件尾,读到的字符会填进长度为
4
4
4的数组buf4
中,其返回的是读到的字符个数。要求用这个API实现读
n
n
n个字符的操作,返回实际读到的字符个数,并且将读入字符也填进输入的数组。
用一个指针标记应该填的哪一个位置,然后只要没读完
n
n
n个字符,就进行while循环,然后调用read4
来尝试读
4
4
4个字符,读完之后填进参数buf
里,如果填好
n
n
n个了,则直接返回
n
n
n;填好之后,看一下当前读过了多少个字符,如果没读够
4
4
4个,则说明读到文件尾了,则返回已经读了多少个字符。代码如下:
class Solution {
public:
/**
* @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;
char buf4[4];
while (res < n) {
int x = read4(buf4);
for (int i = 0; i < x; i++) {
buf[res++] = buf4[i];
if (res == n) return res;
}
if (x < 4) break;
}
return res;
}
};
时间复杂度 O ( n ) O(n) O(n),空间 O ( 1 ) O(1) O(1)。