zoukankan      html  css  js  c++  java
  • ✡ leetcode 158. 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.

    和157题一样,区别在于可以对一个文件多次使用read

    那么区别就是在于如果之前调用过一次read,可能由于调用了read4的原因,会出现多读了几个字母(小于4个),那么设定一个变量即可。存储当前多读取的字母长度和字母。

    1、需要注意的点:多次调用的时候,moreChars里的字母可能没有用完。

    /* 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
         */
        private int len = 0;
        private char[] moreChars = new char[3];
        public int read(char[] buf, int n) {
            if (n < 1){
                return 0;
            }
            int result = 0;
            if (len != 0){
                int count = Math.min(n, len);
                for (int i = 0; i < count; i++){
                    buf[i] = moreChars[i];
                    result++;
                }
                for (int i = 0; i < (len - count); i++){
                    moreChars[i] = moreChars[count + i];
                }
                len -= count;
            }
            char[] chars = new char[4];
            int times = (n - result) / 4;
            for (int i = 0; i < times; i++){
                int count = read4(chars);
                for (int j = 0; j < count; j++){
                    buf[result + j] = chars[j];
                }
                result += count;
                if (count < 4){
                    return result;
                }
            }
            if (n == result){
                return result;
            }
            int count = read4(chars);
            for (int i = 0; i < Math.min(n - result, count); i++){
                buf[result + i] = chars[i];
            }
            if (n - result < count){
                len = count - n + result;
                for (int i = 0; i < len; i++){
                    moreChars[i] = chars[n - result + i];
                }
            }
            result += Math.min(n - result, count);
            return result;
        }
    }
  • 相关阅读:
    决定你人生高度的,不是你的才能,而是你的态度
    享受六一的最后几分钟
    DB9 公头母头引脚定义及连接
    bzoj3207--Hash+主席树
    bzoj1901 [ Zju2112 ] --树状数组套主席树
    bzoj1723 [ Usaco2009 Feb ] --前缀和(水题)
    bzoj3932 [ CQOI2015 ] --可持久化线段树
    bzoj3037--贪心
    bzoj3388 [ Usaco2004 Dec ] (神奇的解法)
    bzoj2693--莫比乌斯反演+积性函数线性筛
  • 原文地址:https://www.cnblogs.com/xiaoba1203/p/6109605.html
Copyright © 2011-2022 走看看