zoukankan      html  css  js  c++  java
  • 从文件中读取字符-多次调用read characters from file multiple calls

    [抄题]:

    接口:int read4(char * buf)一次从文件中读取 4 个字符。
    返回值是实际读取的字符数。 例如,如果文件中只剩下 3 个字符,则返回 3。
    通过使用read4 接口,实现从文件读取 n 个字符的函数int read(char * buf,int n)

     [暴力解法]:

    时间分析:

    空间分析:

    [思维问题]:

    [一句话思路]:

    buffer是缓冲区,buf是缓存。

    [输入量]:空: 正常情况:特大:特小:程序里处理到的特殊情况:异常情况(不合法不合理的输入):

    [画图]:

    1. 用数组实现队列的原理是:进入时是tail移动,出去时是head移动,形成模拟队列

    [一刷]:

    1.  i < n表示内存需求未被满足,head < tail就正常读取。入队时不需要i++,read4已带。
    2. head tail都要初始化为0

    [二刷]:

    [三刷]:

    [四刷]:

    [五刷]:

      [五分钟肉眼debug的结果]:

    [总结]:

    buffer是缓冲区,buf是内存

    [复杂度]:Time complexity: O(n) Space complexity: O(n)

    [英文数据结构或算法,为什么不用别的数据结构或算法]:

    数组,一次只能存4个,空间固定

    [其他解法]:

    [Follow Up]:

    [LC给出的题目变变变]:

     [代码风格] :

    /* 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
         */
         char[] buffer = new char[4];
         int head = 0;
         int tail = 0;
         
        public int read(char[] buf, int n) {
            int i = 0;
            while (i < n) {
                if (head == tail) {
                    head = 0;
                    tail = read4(buffer);
                    if (tail == 0) {
                        break;
                    }
                }
                while (head < tail && i < n) {
                    buf[i++] = buffer[head++];
                }
            }
            return i;
        }
    }
    View Code
  • 相关阅读:
    vue store状态存储管理
    Git分支管理
    oracle事务不能回滚的原因
    vue教程(四)--其他实用用法补充
    vue教程(三)-slotkeep-alive的使用
    vue教程(二)--过滤器和监视改动功能
    vue教程(一)-html使用vue
    Linux后台命令导入MySQL语句
    CentOS6下的ElasticSearch运行步骤
    浅谈JAVA代码优化
  • 原文地址:https://www.cnblogs.com/immiao0319/p/8447964.html
Copyright © 2011-2022 走看看