The API: int read4(char *buf) reads 4 characters at a time from a file.
The return value is the actual number of characters read. For example, it returns 3 if there is only 3 characters left in the file.
By using the read4 API, implement the function int read(char *buf, int n) that reads n characters from the file.
Note:
The read function may be called multiple times.
Solution:需先讀Cache
思路:
The only thing is when you call read4() which reads 4 bytes into your buffer you might read more than you need, so you want to store those bytes in the structure, and next time you call read will start from those stored bytes, then read more from the file.
變化是這樣:比如先call了n=3,然后call n=5,那么第一次就讀入了4個char嘹锁,第二次call應(yīng)該把上一次的最后一個char拿來。也就是說要有個cache取緩存已讀取的字符剧董,然后從這個cache里面取。
Time Complexity: O(N) Space Complexity: O(1)
Solution Code:
/* 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[] prevBuf = new char[4];
int prevSize = 0;
int prevIndex = 0;
public int read(char[] buf, int n) {
int counter = 0;
while (counter < n) {
if (prevIndex < prevSize) {
buf[counter++] = prevBuf[prevIndex++];
} else {
prevSize = read4(prevBuf);
prevIndex = 0;
if (prevSize == 0) {
// no more data to consume from stream
break;
}
}
}
return counter;
}
}