Easy Java Solution for Both Questions 157 & 158


  • 0

    For question 157, Read N Characters Given Read4. What we only need to do is keep a global counter and loop through the returned byte array.

    public int read(char[] dest, int n) {
            int globalStart = 0;
            char[] localBuffer = new char[SIZE];
            for (int i = 0; i < n; i += SIZE) {
                int count = read4(localBuffer);
    
                int start = 0;
                for (int j = i; j < n && start < count; j++) { // start < count important
                    dest[globalStart++] = localBuffer[start++];
                }
    
                if (count < SIZE) {
                    // No more data
                    break;
                }
            }
    
            return globalStart;
        }
    

    For question 158, Read N Characters Given Read4 II - Call multiple times. The only difference here is that we need to apply a cache (implemented by a queue/linked list) for holding characters left by the last call. With the solution for 157 on hand, it is quite easy to add few more checks.

    public class Solution extends Reader4 {
        public static final int SIZE = 4;
        public Queue<Character> cache = new LinkedList<>();
    
        /**
         * @param buf Destination buffer
         * @param n   Maximum number of characters to read
         * @return    The number of characters read
         */
        public int read(char[] dest, int n) {
            if (n == 0) return 0;
            int globalStart = 0;
    
            // Check cache
            if (cache.size() > 0) {
                int i = 0;
                int minSize = Math.min(cache.size(), n);
                while (i < minSize) {
                    System.out.println("[min size " + minSize + "]");
                    dest[globalStart++] = cache.poll();
                    i++;
                }
            }
    
            // Pull new data if needed
            char[] localBuffer = new char[SIZE];
            for (int i = globalStart; i < n; i += SIZE) {
                int count = read4(localBuffer);
    
                int start = 0;
                for (int j = i; j < n && start < count; j++) { // start < count important
                    dest[globalStart++] = localBuffer[start++];
                }
    
                // check remaining items (n ended)
                if (start < count) {
                    for (int k = start; k < SIZE && k < count; k++) {
                        cache.add(localBuffer[k]);
                    }
                }
    
                if (count < SIZE) {
                    // No more data
                    break;
                }
            }
    
            return globalStart;
        }
    }
    

Log in to reply
 

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