Java 2ms, keeping a buffer end pointer and a char[4] temp array


  • 0
    Y
    public class Solution extends Reader4 {
        public int read(char[] buf, int n) {
            int bufEnd = 0; // exclusive
            char[] temp = new char[4];
            while (n > bufEnd) {
                int read = read4(temp);
                for (int i = 0; i < read && bufEnd < n; i++) {
                    buf[bufEnd++] = temp[i];
                }
                if (read < 4) {
                    break;
                }
            }
            return bufEnd;
        }
    }

  • 0
    M

    Thank you for your solution. Here is a point which I don't understand. Why you use read4() method to read temp, which is empty? And how could read be less than 4 if you define temp as a char array with length of 4? Really appreciate your help!


  • 0
    Y

    @Michael_Xu, we know nothing about the source file which is hiding behind the API, so we don't know when we reach the end of that file when the chars available are less than 4, and that is why the read4 api needs to not only fill in an array, but also return a number


  • 0
    Y

    besides, temp is not being read, it is being written. the file that is being read is hidden behind that API, and we have no idea whatsoever, except the int returned from read4 API


  • 0
    M

    Got it. Thank you so much! I still need more practice


Log in to reply
 

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