Solution by azrush


  • 0
    A

    Approach

    Intuition

    Have a local buffer of size 4.

    Algorithm

    Have a local buffer of size 4. Each time read is called, we check if there is anything in the local buffer already and use that first. Then we call read4 as many times as possible to load new chars to local buffer as well as adding to the output buf until we have enough chars to return or there is no more chars to load (when read4 returns 0).

    See more explanation in the code.

    Java

    /* The read4 API is defined in the parent class Reader4.
          int read4(char[] buf); */
    
    public class Solution extends Reader4 {
    
        private char[] local = new char[4];
        private int localIndex = 4;
        private int localSize = 0;
    
        /**
         * @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) {
            if (n == 0) return 0;
    
            int cnt = 0;
    
            // Use chars in the local buffer first.
            while (localIndex < localSize && cnt < n) {
                buf[cnt++] = local[localIndex++];
            }
    
            // While we need more chars
            while (cnt < n) {
                localSize = read4(local); // load local buffer
                if (localSize == 0) break; // if there is no more char, just break
                localIndex = 0;
    
                // Also add chars to the output buf
                while (localIndex < localSize && cnt < n) {
                    buf[cnt++] = local[localIndex++];
                }
            }
    
            return cnt;
        }
    }
    

    Complexity Analysis

    • Time complexity : $$O(n)$$.

    This should be intuitive enough. We only load each char once.


Log in to reply
 

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