• ✡ leetcode 157. Read N Characters Given Read4 利用read4实现read --------- java


    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.

    read4(char[] buf)指的是读取4个数,存储在buf中,然后返回成功读取的数目,如果不够四个,那么就返回剩余数目的字符。

    实现的read(char[] buf, int n)功能类似,只不过将4改为了n,需要输入而已。(这里一个例子只会读取一次read)

    刚开始做的时候理解错了,以为是读取buf中的字符,导致提交失败。

    方法是:先读取n/4次read4,如果期间有出现了不等于4的情况,那么返回结果。

        然后读取最后一次,需要判断的是:1、如果刚好读完了,直接返回结果

                        2、判断n-result和读取数目num的大小,选择小的,读取并返回数目。

    /* 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) {
            if (n < 1){
                return 0;
            }
            int time = n / 4;
            int result = 0;
            char[] chars = new char[4];
            for (int i = 0; i < time; i++){
                int num = read4(chars);
                for (int j = 0; j < num; j++){
                    buf[i * 4 + j] = chars[j];
                }
                if (num != 4){
                    result += num;
                    return result;
                } else {
                    result += 4;
                }
            }
            if (n - result == 0){
                return result;
            }
            int num = read4(chars);
            for (int i = 0; i < Math.min(n - result, num); i++){
                buf[result + i] = chars[i];
            }
            result += Math.min(n - result, num);
            return result;
        }
    }
  • 相关阅读:
    寒假瞎搞系列(5)
    《亿级用户下的新浪微博平台架构》阅读笔记
    《蚂蚁金服11.11:支付宝和蚂蚁花呗的技术架构及实践》阅读笔记
    《游戏服务器的架构演进(完整版)》阅读笔记
    阅读架构漫谈(四)笔记
    阅读架构漫谈(三)笔记
    阅读架构漫谈(二)笔记
    以《淘宝网》为例,描绘质量属性的六个常见属性场景
    阅读架构漫谈(一)笔记
    假期周进度总结2
  • 原文地址:https://www.cnblogs.com/xiaoba1203/p/6109360.html
Copyright © 2020-2023  润新知