157 Read N Characters Given Read4
1. Question
2. Implementation
/* 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) {
boolean eof = false;
char[] buffer = new char[4];
int index = 0;
while (!eof && index < n) {
int size = read4(buffer);
if (size < 4) {
eof = true;
}
int bytes = Math.min(n - index, size);
for (int i = 0; i < bytes; i++) {
buf[index++] = buffer[i];
}
}
return index;
}
}3. Time & Space Complexity
Last updated