Clean accepted java solution


  • 10
    R

    The key is to store memorized variable in the class level and remember offset position and remaining number of elements.

    /* The read4 API is defined in the parent class Reader4.
          int read4(char[] buf); */
    
    public class Solution extends Reader4 {
        
        private int offSet = 0;
        private int remaining = 0;
        private boolean isEndOfFile = false;
        private char[] buffer = new char[4];
        
        /**
         * @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 readBytes = 0;
            while (readBytes < n && (remaining != 0 || !isEndOfFile)) {
                int readSize = 0;
                if (remaining != 0) {
                    readSize = remaining;
                } else {
                    offSet = 0;
                    readSize = read4(buffer);
                    if (readSize != 4) {
                        isEndOfFile = true;
                    }
                }
                int length = Math.min(n - readBytes, readSize);
                for (int i= offSet; i<offSet + length; i++) {
                    buf[readBytes++] = buffer[i];
                }
                remaining = readSize - length;
                if (remaining != 0) {
                    offSet += length;
                }
            }
            return readBytes;
        }
    }

  • 1

    Best solution I have ever found. The hard part of this question is how to understand the question itself.


  • 0
    X
    Best solution!

Log in to reply
 

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