Java two methods, using LinkedList and buffer pointer


  • 0

    Method 1, using a linkedlist to store the exceed char left over from a read action. Next time we call read, we first get char from this linkedlist.

        private LinkedList<Character> exceed = new LinkedList<>();
        public int read(char[] buf, int n) {
            int i = 0, sum = 0, count = 0, actualread = 0;
            char[] tmp = new char[4];
            if (!exceed.isEmpty()) {
                int size = exceed.size();
                for (; i < Math.min(size, n); i++) {
                    buf[i] = exceed.pollFirst();
                }
            }
            while (i < n) {
                actualread = read4(tmp);
                count = Math.min(n-i, actualread);
                for (int j = 0; j < count; j++) {
                    buf[i++] = tmp[j];
                    sum++;
                }
                if (actualread < 4) break;
            }
            while (count < actualread) exceed.add(tmp[count++]);
            return i;
        }
    

    Method 2: keep a pointer in the buffer of size 4 (argument of the read4 method) and also the capacity of the buffer of size 4. keep retrieving char from the buffer of size 4 till we reach the end.

        private int bufsize = 0, bufptr = 0;
        private char[] buffer = new char[4];
        public int read(char[] buf, int n) {
            int i = 0;
            while (i < n) {
                if (bufptr == bufsize) {
                    bufsize = read4(buffer);
                    bufptr = 0;
                }
                if (bufsize == 0) break;
                buf[i++] = buffer[bufptr++];
            }
            return i;
        }
    

Log in to reply
 

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