My 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
*/
public int read(char[] buf, int n) {
char[] arr = new char[4];
int counter = 0;
int num = 4;
while (num == 4 && counter < n) {
num = read4(arr);
for (int i = counter; i < n && i < counter + num; i++) {
buf[i] = arr[i - counter];
}
counter = Math.min(n, counter + num);
}
return counter;
}
}
reference:
https://discuss.leetcode.com/topic/52449/java-solution-easy-to-understand
没能自己做出来。没理解题目的意思。后来才知道什么意思。
其实就是每次读4个,读出 n 个 拷贝到 char[] 里面去。
注意点:
1 . 文件里面的字符个数可能 < n
所以 while 判断条件不能只用 counter < n
2 . counter = Math.min(n, counter + temp);
Anyway, Good luck, Richardo! — 09/20/2016