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.
Idea: The problem statement is not quite clear. The note "the read function may be called multiple times" means the current read() may continue fro the middle of a read4() done in the last read()
For example:
First read(), read 3 characters from 15 characters original data
1): read4(), but we only need 3, so we have the fourth character read by not assigned to the destination.
Second read(): read 6 characters from the same data
1)now we can only read 1, since the forth character has been read by the first read(), we need to first use this character read in the first read() but not assigned.
2) continue to repeat read4() until we meet the 6 characters requirement.
If the problem is understood clearly, we can design the algorithm as following:
1) use a char[] to cache the characters read in the last time
2) use a pointer "offset" to point to the end of the last read()
3) if there are some characters left in the last read(), we first copy these characters to the destination buf[].
4) continue with the rest of reading by using read4().
Time: O(n) Space: O(1)
Code:
public class Solution extends Reader4 {
/**
* @param buf Destination buffer
* @param n Maximum number of characters to read
* @return The number of characters read
*/
char[] buffer=new char[4];
int offset=0,bufSize=0;
public int read(char[] buf, int n) {
int readBytes=0;
boolean eof=false;
while(readBytes<n&&eof==false)
{
if(bufSize==0)
{
bufSize=read4(buffer);
if(bufSize<4)
eof=true;
}
int actuallyRead=Math.min(n-readBytes,bufSize);
for(int i=0;i<actuallyRead;i++)
buf[readBytes+i]=buffer[offset+i];
offset=(offset+actuallyRead)%4;
bufSize-=actuallyRead;
readBytes+=actuallyRead;
}
return readBytes;
}
}
No comments:
Post a Comment