IO Buffer & H-Index
Read N Characters Given Read4
读一个文件最终有两个结果
- 把文件读完了,但是没有读到n个字符,返回总过读了多少个字符。
- 文件读完了或者没有读完,返回n。
/* 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
*/
public int read(char[] buf, int n) {
int readBytes = 0;
char[] temp = new char[4];
boolean eof = false;
while (!eof && readBytes < n) {
int count = read4(temp);
if (count < 4) {
eof = true;
}
int length = Math.min(count, n - readBytes);
for (int i = 0; i < length; i++) {
buf[readBytes++] = temp[i];
}
}
return readBytes;
}
}
Read N Characters Given Read4 II - Call multiple times
比如我们有一个文件叫[a, b]。如果第一次我们调用read(buf, 1),我们能在文件里读到[a]。但是如果我们坚持了上一题的做法,read4这个方法已经把整个文件都读完了,那我们再次调用read(buf, 1),我们无法读到任何字符。因此在这题里,我们需要在全局里cache下上一次read4读出的,但是在上一次的结果里没有被用到的characters。
/* 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
*/
int remaining = 0, offset = 0;
boolean eof = false;
char[] temp = new char[4];
public int read(char[] buf, int n) {
int readBytes = 0;
while (readBytes < n && (!eof || remaining != 0)) {
int readLength = 0;
if (remaining != 0) {
readLength = remaining;
remaining = 0;
} else {
offset = 0;
readLength = read4(temp);
if (readLength < 4) {
eof = true;
}
}
int length = Math.min(readLength, n - readBytes);
for (int i = offset; i < offset + length; i++) {
buf[readBytes++] = temp[i];
}
remaining = readLength - length;
if (remaining != 0) {
offset += length;
}
}
return readBytes;
}
}