美文网首页
157. Read N Characters Given Rea

157. Read N Characters Given Rea

作者: jluemmmm | 来源:发表于2021-08-10 00:57 被阅读0次

给定一个文件,该文件只能通过给定的 read4 方法读取,请实现一个方法使其能够读取 n 个字符。返回读取的字符个数,并将读取的字符存储到buf中

read4方法:

  • API read4可以从文件中读取 4 个连续的字符串,并且将它们写入缓存数组 buf 中
  • 返回实际读取的字符个数
  • 注意 read4() 自身拥有文件指针,类似于c语言中的 FILE * fp

思路:循环,用一个定长为4的空间的数组进行中转,到达n的阈值的情况下停止存储。

  • 时间复杂度O(N),空间复杂度O(1)
  • Runtime: 68 ms, faster than 87.36%
  • Memory Usage: 38.9 MB, less than 52.75%
/**
 * @param {function} read4()
 * @return {function}
 */
var solution = function(read4) {
  /**
   * @param {character[]} buf Destination buffer
   * @param {number} n Number of characters to read
   * @return {number} The number of actual characters read
   */
  return function(buf, n) {
    let copiedChars = 0;
    let readChars = 4;
    const buf4 = new Array(4);
    
    while (copiedChars < n && readChars === 4) {
      readChars = read4(buf4);
      for(let i = 0; i < readChars; i++) {
        if (copiedChars === n) {
          return n;
        }
        buf[copiedChars] = buf4[i];
        copiedChars++
      }
    }
    return copiedChars;
  };
};

相关文章

网友评论

      本文标题:157. Read N Characters Given Rea

      本文链接:https://www.haomeiwen.com/subject/joztbltx.html