zoukankan      html  css  js  c++  java
  • ✡ leetcode 157. Read N Characters Given Read4 利用read4实现read --------- java

    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 will only be called once for each test case.

    read4(char[] buf)指的是读取4个数,存储在buf中,然后返回成功读取的数目,如果不够四个,那么就返回剩余数目的字符。

    实现的read(char[] buf, int n)功能类似,只不过将4改为了n,需要输入而已。(这里一个例子只会读取一次read)

    刚开始做的时候理解错了,以为是读取buf中的字符,导致提交失败。

    方法是:先读取n/4次read4,如果期间有出现了不等于4的情况,那么返回结果。

        然后读取最后一次,需要判断的是:1、如果刚好读完了,直接返回结果

                        2、判断n-result和读取数目num的大小,选择小的,读取并返回数目。

    /* 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
         */
        public int read(char[] buf, int n) {
            if (n < 1){
                return 0;
            }
            int time = n / 4;
            int result = 0;
            char[] chars = new char[4];
            for (int i = 0; i < time; i++){
                int num = read4(chars);
                for (int j = 0; j < num; j++){
                    buf[i * 4 + j] = chars[j];
                }
                if (num != 4){
                    result += num;
                    return result;
                } else {
                    result += 4;
                }
            }
            if (n - result == 0){
                return result;
            }
            int num = read4(chars);
            for (int i = 0; i < Math.min(n - result, num); i++){
                buf[result + i] = chars[i];
            }
            result += Math.min(n - result, num);
            return result;
        }
    }
  • 相关阅读:
    70. Climbing Stairs(动态规划)
    53. Maximum Subarray(动态规划)
    PAT 1045. Favorite Color Stripe
    PAT 1044. Shopping in Mars
    分治策略
    时间复杂度和空间复杂度分析(转载)
    [转载]论坛中某位达人自己编写的Morlet连续小波变换程序
    连续小波时频图绘制原理    连续小波变换尺度与信号频率的关系
    Matlab中wavedec使用學習及詳解
    [转载]转载:小波分解层数与尺度的关系
  • 原文地址:https://www.cnblogs.com/xiaoba1203/p/6109360.html
Copyright © 2011-2022 走看看