157.Read N Characters Given Read4 (Easy)

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 theread4API, implement the functionint read(char *buf, int n)that reads n characters from the file.

Note:
Thereadfunction will only be called once for each test case.

Solution 1: Iterative O(n); O(1)

possible case: the characters' number of file is less than n.

    /**
     * Solution1: Iterative O(n); O(1)
     * Use a for loop, each time use a temp buffer to store the result of read4.
     * Copy from temp buffer to the parameter “buf”.
     * Check if it's the end of the file, if yse, return the smaller between current read char numbers and n.
     */
    public int read(char[] buf, int n) {
        for (int i = 0; i < n; i += 4) {
            char[] temp = new char[4];
            int len = read4(temp); //use a temp buffer to store the result of read4

            for (int j = 0; j < len; j++) { // copy from temp buffer to buf
                buf[i + j] = temp[j];
            }

            if (len < 4) { //check if it's the end of the file
                return Math.min(i + len, n); //cannot return i + len, since n may be less than i + len.
            } //possible case: the characters' number of file is less than n.
        }
        return n;
    }

    int read4(char[] buf) {
        return 4;
    }

利扣 妖舞扒变形,给了read4,但是实现按行read,会有'/n'为行终止,这题开始没理清题意,以为总是以行终止作为结束,就没考虑读完的情况,后来面试官提醒说不一定最后是行终止字符才发现少了个if,悲剧, 大家一定要问清题意再作答啊

http://www.1point3acres.com/bbs/thread-294662-1-1.html

results matching ""

    No results matching ""