从文件中读取字符-多次调用read characters from file multiple calls

时间:2023-03-10 01:34:21
从文件中读取字符-多次调用read characters from file multiple calls

[抄题]:

接口:int read4(char * buf)一次从文件中读取 4 个字符。
返回值是实际读取的字符数。 例如,如果文件中只剩下 3 个字符,则返回 3。
通过使用read4 接口,实现从文件读取 n 个字符的函数int read(char * buf,int n)

[暴力解法]:

时间分析:

空间分析:

[思维问题]:

[一句话思路]:

buffer是缓冲区,buf是缓存。

[输入量]:空: 正常情况:特大:特小:程序里处理到的特殊情况:异常情况(不合法不合理的输入):

[画图]:

  1. 用数组实现队列的原理是:进入时是tail移动,出去时是head移动,形成模拟队列

从文件中读取字符-多次调用read characters from file multiple calls

[一刷]:

  1. i < n表示内存需求未被满足,head < tail就正常读取。入队时不需要i++,read4已带。
  2. head tail都要初始化为0

[二刷]:

[三刷]:

[四刷]:

[五刷]:

[五分钟肉眼debug的结果]:

[总结]:

buffer是缓冲区,buf是内存

[复杂度]:Time complexity: O(n) Space complexity: O(n)

[英文数据结构或算法,为什么不用别的数据结构或算法]:

数组,一次只能存4个,空间固定

[其他解法]:

[Follow Up]:

[LC给出的题目变变变]:

[代码风格] :

/* The read4 API is defined in the parent class Reader4.
int read4(char[] buf); */ public class Solution extends Reader4 {
/**
* @param buf destination buffer
* @param n maximum number of characters to read
* @return the number of characters read
*/
char[] buffer = new char[4];
int head = 0;
int tail = 0; public int read(char[] buf, int n) {
int i = 0;
while (i < n) {
if (head == tail) {
head = 0;
tail = read4(buffer);
if (tail == 0) {
break;
}
}
while (head < tail && i < n) {
buf[i++] = buffer[head++];
}
}
return i;
}
}