Java solution. No if(s).


  • 4
    Z
    public class Solution extends Reader4 {
        private char[] buffer = new char[4];
        private int bufferBytes = 0;
        private int bufferPointer = 0;
    
        public int read(char[] buf, int n) {
            int copy = Math.min(n, bufferBytes);
            System.arraycopy(buffer, bufferPointer, buf, 0, copy);
            bufferBytes -= copy;
            bufferPointer += copy;
    
            int total = copy;
            int readBytes = 4;
            while (total < n && readBytes == 4) {
                readBytes = read4(buffer);
                copy = Math.min(n-total, readBytes);
                bufferBytes = readBytes - copy;
                bufferPointer = copy;
                System.arraycopy(buffer, 0, buf, total, copy);
                total += copy;
            }
    
            return total;
        }
    }
    
    1. copying data from the buffer;
    2. copying data from the underlying stream;
    3. maintain bufferPointer/bufferBytes in the both sections.
      No if(s).

  • 0
    F

    the best explanation and code! When I update bufferPointer, I also copy%4 just in case.


  • 0
    Z

    I don't understand your comment. Could you please elaborate?


Log in to reply
 

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