This is the solution about Leetcode - Read N Characters Given Read4.

Description

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.

Solution

Analysis

这一题意思是:有一个文件,读取n个字符,n可能会比文件总共包含的字符数要大,read4 API通常读4个字符,如果读到最后文件中的字符少于4个则返回剩下数目。所以这里需要留意两点:
1.n比文件字符数小时,每次读4个可能会超出n
2.n比文件字符数大时,只读到文件末尾

Solution1

Use System.arraycopy to copy from read4 to buf.

Solution2

Use AC solution.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
/* The read4 API is defined in the parent class Reader4.
int read4(char[] buf); */
public class Solution1 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) {
int curLen = 0;
while(curLen < n) {
char[] tempBuf = new char[4];
//read4: read from file and save into tempBuf, return the number of read.
int len = read4(tempBuf);
System.arraycopy(tempBuf,0,buf,curLen,Math.min(len,n-curLen));
if(len<4) return Math.min(curLen+len,n);
curLen += 4;
}
return n;
}
}
public class Solution2 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) {
int index = 0;
int count = 4;
//if count!=4, it represents read to the end of file or the end of n characters
while(count==4) {
char[] tempBuf = new char[4];
count = read4(tempBuf);
//prevent from getting more than what we need
count = Math.min(count,n-index);
//copy from tempBuf to buf
for(int i=0; i<count; i++) {
buf[index++] = tempBuf[i];
}
}
return index;
}
}