首页 > 代码库 > Leetcode: Read N Characters Given Read4

Leetcode: Read N Characters Given Read4

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是一个读文件的函数,只能读4个char。
char [] buffer = new char[4]
int size = read4(buffer)
这里read4将空buffer改成了file的 4 个char.
然后关于parameter的定义是:

* @param buf Destination buffer,我后来理解这个应该是个足够大的buffer,需要将读到的file放到这个buffer里面去
* @param n Maximum number of characters to read,想要读n个char,但是有可能读不到那么多,因为有可能n比文件的size大
* @return The number of characters read,实际读到的char数,小于等于n

由于不知道文件的大小,所以只能一次一次用4个char的buffer用read4去读,存在以下两种结束方式(假设文件大小为size):

1. n >> size, 比如n = 50, size = 23, 最后一次读的大小为<4, 下一次就不读了,然后把这一次读的char数oneRead赋给目标buf

至于n = 50, size = 20, 最后一次读到0个,不会进行赋值,下一次也不读了

2. n << size,比如n = 23, size = 50, read4每次会读满4个,但是我们只取3个,取零头的方法是int actRead = Math.min(n-haveRead, oneRead); 下一次OneRead+haveRead>n, 也就停止了

想清楚了这些,就可以写了

 1 /* The read4 API is defined in the parent class Reader4. 2       int read4(char[] buf); */ 3  4 public class Solution extends Reader4 { 5     /** 6      * @param buf Destination buffer 7      * @param n   Maximum number of characters to read 8      * @return    The number of characters read 9      */10     public int read(char[] buf, int n) {11        char[] buffer = new char[4];12        int haveRead = 0;13        boolean lessthan4 = false;14        15        while (!lessthan4 && haveRead < n) {16            int oneRead = read4(buffer);17            if (oneRead < 4) lessthan4 = true;18            int actRead = Math.min(n-haveRead, oneRead);19            while (int i=1; i<=actRead; i++) {20                buf[haveRead+i-1] = buffer[i-1];21            }22            haveRead += actRead;23        }24        return haveRead;25     }26 }

 

 

Leetcode: Read N Characters Given Read4