ReadNCharactersGivenRead4 [source code]


public class ReadNCharactersGivenRead4 {
static
/******************************************************************************/
/* 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) {
        int i;
        for (i = 0; i < n; i += 4) {
            char[] tmp = new char[4];
            int len = read4(tmp);
            for (int j = 0; j < len; j++) {
                if (i + j >= n) return n;
                buf[i + j] = tmp[j];
            }
            if (len < 4) return i + len;
        }
        return n;
    }
}
/******************************************************************************/
static class Reader4 {
    int read4 (char[] buf) {
        return 0;
    }
}

    public static void main(String[] args) {
        ReadNCharactersGivenRead4.Solution tester = new ReadNCharactersGivenRead4.Solution();
    }
}

这个题目刚开始没有理解这个问题实际的意思, 以为buf就是file, 实际上这里的buf就是一个缓冲区, 可以理解是最后存储的地方(利用mutability).
而返回值的作用就是用来表达buf中的有效长度, 前面好几个类似的array问题好像其实是做过这样的类似的题目的;

这个题目绝对是LeetCode做到现在以来题目的描述最混乱的一个了, 难怪有90%的downvote; 而且题目的设定对于不是使用C/C++
的人来说太不利了;

最后好歹还是AC了, 速度是1(28), 最优解;

题目读懂的话, 这个问题本身并不复杂, 就是要用n和Enf Of File两个条件来控制termination就行了;

这个题目真正写代码的时候一个稍微有点烦人的地方就是这里index类的变量和length类的变量交叉混用特别多, 所以你自己写一个变量的时候, 要注意不停提醒自己这个(比如: i + j)到底是index还是length;


这个是discussion里面看到的一个最优解:

public class Solution extends Reader4 {  
    public int read(char[] buf, int n) {  
        for(int i = 0; i < n; i += 4){  
            char[] tmp = new char[4];  
            // 将数据读入临时数组  
            int len = read4(tmp);  
            // 将临时数组拷贝至buf数组,这里拷贝的长度是本次读到的个数和剩余所需个数中较小的  
            System.arraycopy(tmp, 0, buf, i, Math.min(len, n - i));  
            // 如果读不满4个,说明已经读完了,返回总所需长度和目前已经读到的长度的较小的  
            if(len < 4) return Math.min(i + len, n);  
        }  
        // 如果循环内没有返回,说明读取的字符是4的倍数  
        return n;  
    }  
}

整体的思路其实是类似的.


Problem Description

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.

Difficulty:Easy
Total Accepted:32K
Total Submissions:110.3K
Contributor: LeetCode
Companies
facebook
Related Topics
string
Similar Questions
Read N Characters Given Read4 II - Call multiple times

results matching ""

    No results matching ""