Java solution like other posts


  • 0
    D
    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 = 0;
            while (index < bsize) { // first read from buf4 from the previous call
                if (i == n)
                    return i;
                buf[i++] = buf4[index++];
            }
            index = 0; // here, all data in buf4 is read, so reset index and bsize
            bsize = 0;
            int j = 0, r4 = 0;
            while (i < n) { // call read4 and fill out buf
                r4 = read4(buf4);
                if (r4 == 0) // reached end of file
                    return i;
                j = 0;
                while (j < r4 && i < n) { // copy buf4 to buf
                    buf[i++] = buf4[j++];
                }
            }
            if (j < r4) { // buf4 still contains uncopied data, so keep it for next call
                index = j;
                bsize = r4;
            }
            return i;
        }
        private char[] buf4 = new char[4];
        private int bsize = 0;
        private int index = 0;
    }
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.