


思路:这题很奇怪,返回值是int,但是却要输出buf才行(不然就报错)。题目也很难理解。建议回炉重造。复习到这题时候,建议直接回leetcode discussion部分去看别人解释题目意思。我看题目明明说只能call一次read4函数,但是大家答案中都有循环,都多次调用了,这样可以吗,我也不太确定。但是看到大家都这样做,我也这样做了。理解题目意思之后也比较简单吧。没啥好说的。直接放代码好吧:
/**
* 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 Number of characters to read
* @return The number of actual characters read
*/
public int read(char[] buf, int n) {
char[] temp = new char[4];//新建一个字符数组用来表示每次read4之后的buf
int count = read4(temp);
if(count < 4){
if(n < count){
for(int i = 0; i < n; i++){
buf[i] = temp[i];
}
return n;
}else if(n >= count){
for(int i = 0; i < count; i++){
buf[i] = temp[i];
}
return count;
}
}else{ //count = 4
if(n <= 4){
for(int i = 0; i < n; i++){
buf[i] = temp[i];
}
return n;
}else{
int c = 0;
int num = 4;
List<Character> list = new ArrayList();
for(int i = 0; i < 4; i++){
list.add(temp[i]);
}
while(num == 4){
num = read4(temp);
if(num == 4){
for(int i = 0; i < 4; i++){
list.add(temp[i]);
}
c++;
}else{
for(int i = 0; i < num; i++){
list.add(temp[i]);
}
break;
}
}
int len = (c+1)*4 + num;
int res = Math.min(n, len);
for(int i = 0; i < res; i++){
buf[i] = list.get(i);
}
return res;
}
}
return 0;
}
}
总结:
- 没啥好说的,这题就很怪,如果不是有facebook tag,这题目我觉得是没有什么意义。最近也比较懒,自己做出来的题目就不太愿意再去看别人的解答,其实别人的解答还是有很多很高效的解答的。希望赶紧调整状态。
本文深入探讨了read4 API的使用方法及如何处理缓冲区读取的问题。通过具体实例,解析了在不同情况下如何正确调用read4 API以实现高效的数据读取。同时,分享了在实现过程中的注意事项和常见错误避免策略。
228

被折叠的 条评论
为什么被折叠?



