问题描述
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 will only be called once for each test case.
题目链接:
思路分析
利用已有的read4 API来实现一个可以读取任意长度n个字符的read方法,如果buf中的字符数小于n则返回buf的字符数。
一直调用read4,直到count大于n了(buf > n)或者read4的返回值不为4了(buf < n)。方法的返回值为n和读出来的count中较小的那一个。
代码
/* 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
*/
private int prev = 4;
private int count = 0;
private char[] readChars = new char[4];
/*
Basically, call multiple times means, you want to resume where you left off last time.
That means, if there are chars left in readChars (from the Read4 from the previous call of ReadN), you want to transfer them into buffer first.
*/
public int read(char[] buf, int n) {
int total = 0;
/**
EdgeCases:
If N < 4, do you transfer all the remaining chars from previous call or just N?
what if there are still characters left in readChars after transfering N to the buffer? In that case, you still want to pick up from there next time.
**/
while(total < n){
while(prev < count && total < n){
buf[total] = readChars[prev];
prev++;
total++;
}
if(total < n){
count = read4(readChars);
prev = 0;
//You only want to read till N even if there are more chars returned by read4.
int toRead = Math.min(count, n-total);
while(prev < toRead){
buf[total] = readChars[prev];
prev++;
total++;
}
//Done. There are no more chars to read from Read4.
if(count < 4) break;
}
}
return total;
}
}
// Forward declaration of the read4 API.
int read4(char *buf);
class Solution {
public:
/**
* @param buf Destination buffer
* @param n Maximum number of characters to read
* @return The number of characters read
*/
int read(char *buf, int n) {
int temp;
int count = 0;
do{
temp = read4(buf + count);
count += temp;
}while(temp == 4 && count < n);
return min(count,n);
}
};
时间复杂度:未知
反思
对于指针的理解不到位,在内存中的位移可以带到下一个内存的位置上去。