• LeetCode-Read N Characters Given Read4 II


    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 may be called multiple times.

    Solution:

     1 /* The read4 API is defined in the parent class Reader4.
     2       int read4(char[] buf); */
     3 
     4 public class Solution extends Reader4 {
     5     char[] tempBuf = new char[4];
     6     int offset = 4;
     7     int maxLen = 4;
     8 
     9     /**
    10      * @param buf
    11      *            Destination buffer
    12      * @param n
    13      *            Maximum number of characters to read
    14      * @return The number of characters read
    15      */
    16     public int read(char[] buf, int n) {
    17         int ind = 0;
    18         while (offset < maxLen && ind < n) {
    19             buf[ind++] = tempBuf[offset++];
    20         }
    21         if (maxLen < 4) return ind;
    22         
    23         ind = readFile(buf, ind, n);
    24         return ind;
    25     }
    26 
    27     public int readFile(char[] buf, int ind, int n) {
    28         int num = 4;
    29         while (num == 4 && ind < n) {
    30             num = read4(tempBuf);
    31             int end = Math.min(num, n - ind);
    32             for (offset = 0; offset < end; offset++) {
    33                 buf[ind++] = tempBuf[offset];
    34             }
    35         }
    36         maxLen = num;
    37         return ind;
    38     }
    39 }
  • 相关阅读:
    c#数组
    微软原版SQL Helper
    CROSS APPLY和 OUTER APPLY 区别详解
    Excel 开发备忘
    ZPL打印机公用代码
    SQL SERVER 索引维护
    C#调用斑马打印机打印条码标签(支持COM、LPT、USB、TCP连接方式和ZPL、EPL、CPCL指令)
    ZPL打印机命令解释
    在x64平台上调试依赖于x86的WCF服务
    SQL 行转列的两种做法
  • 原文地址:https://www.cnblogs.com/lishiblog/p/5820382.html
Copyright © 2020-2023  润新知