158 Read N Characters Given Read4 II - Call multiple times
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
*/
int bufferIndex = 0;
int readBytes = 0;
char[] buffer = new char[4];
public int read(char[] buf, int n) {
int index = 0;
while (index < n) {
if (bufferIndex < readBytes) {
buf[index++] = buffer[bufferIndex++];
}
else {
readBytes = read4(buffer);
bufferIndex = 0;
if (readBytes == 0) {
break;
}
}
}
return index;
}
}3. Time & Space Complexity
Last updated