Leetcode 157 Read N Characters Given Read4

本文深入探讨了read4 API的使用方法及如何处理缓冲区读取的问题。通过具体实例,解析了在不同情况下如何正确调用read4 API以实现高效的数据读取。同时,分享了在实现过程中的注意事项和常见错误避免策略。

在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
思路:这题很奇怪,返回值是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;
    }
}

总结:

  1. 没啥好说的,这题就很怪,如果不是有facebook tag,这题目我觉得是没有什么意义。最近也比较懒,自己做出来的题目就不太愿意再去看别人的解答,其实别人的解答还是有很多很高效的解答的。希望赶紧调整状态。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值