问题描述
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.
解决思路
通过for循环,每次读取4个,通过System.arraycopy进行拷贝。如果最后length小于4,则返回n和当前位置i加上length之间的最小值。循环结束返回n,则为读取的个数。
问题解惑
-
读取的源数组是什么?
需要自己传入原数组,代码中buffer即为源文件 -
为什么length = read4(buffer)?buffer不就是长度为4吗,直接length = 4不可以吗?
不可以。因为虽然buffer初始化是长度为4的数组,但不一定里面存满4个。length等于的是buffer数组里面有的内容的个数(长度)。 -
length < 4的时候,为什么还直接范围i + length呢?为什么还要再比较一下min? i + length有可能大于n,比如n为30,此时i = 28, length = 3.就需要比较n和i + length的大小。反之,若i = 24,length = 3,同理。
-
System.arraycopy的用法?
System.arraycopy(src, srcStartPos, des, desStartPos, copyLen)
代码
package leetcode;
class Reader4{
public int read4(char[] buf){
return buf.length;
}
}
public class ReadNCharatersGivenRead4 extends Reader4{
public int read(char[] buf, int n) {
for (int i = 0; i < n; i += 4) {
char[] buffer = new char[4];
int length = read4(buffer);
System.arraycopy(buffer, 0, buf, i, length);
if (length < 4) return Math.min(i + length, n);
}
return n;
}
}