【Leetcode】158. Read N Characters Given Read4 II - Call multiple times

该博客介绍了一个C++实现的解决方案,利用给定的read4接口,设计一个函数能读取指定数量的文件字符。函数通过维护一个缓冲区来提高效率,实现了O(n)的时间复杂度和O(1)的空间复杂度。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题目地址:

https://leetcode.com/problems/read-n-characters-given-read4-ii-call-multiple-times/

给定一个接口int read4(char * buf)可以每次从文件中读取 4 4 4个字符,返回值是实际读取的字符数(有可能文件剩下的字符数不够,从而返回小于 4 4 4的数字)。要求通过这个接口,实现从文件读取 n n n个字符的函数,返回值也是实际读取的字符数。这个函数会调用多次。

参考https://blog.csdn.net/qq_46105170/article/details/109482719。代码如下:

class Solution {
 public:
  char buf4[4];
  int head, tail;

  Solution() { head = tail = 0; }

  /**
   * @param buf Destination buffer
   * @param n   Number of characters to read
   * @return    The number of actual characters read
   */
  int read(char *buf, int n) {
    int res = 0;
    while (res < n) {
      if (head == tail) {
        head = 0;
        tail = read4(buf4);
      }
      if (!tail) break;
      while (res < n && head < tail) buf[res++] = buf4[head++];
    }

    return res;
  }
};

时间复杂度 O ( n ) O(n) O(n),空间 O ( 1 ) O(1) O(1)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值