157. Read N Characters Given Read4 - Only calling one time

The API:int read4(char *buf)reads 4 characters at a time from a file.

The return value is the actual number of characters read. For example, it returns 3 if there is only 3 characters left in the file.

By using theread4API, implement the functionint read(char *buf, int n)that readsncharacters from the file.

Example 1:

Input: 
buf ="abc", n = 4

Output:
"abc"

Explanation: The actual number of characters read is 3, which is "abc".

Example 2:

Input: buf = "abcde", n = 5 

Output: "abcde"

Note:
The readfunction will only be called once for each test case.

Thoughts:

  1. Having a position counter: end to keep track the current reading position
  2. return the min of end and the n: min(end,n)
// Forward declaration of the read4 API.
int read4(char *buf);

class Solution {
public:
    /**
     * @param buf Destination buffer
     * @param n   Maximum number of characters to read
     * @return    The number of characters read
     */
    int read(char *buf, int n) {
        int end = 0, lastRead = 4;  // end position returned by read4, lastnumber of chars read
        while(end < n && lastRead == 4){
            lastRead = read4(buf+end);
            end += lastRead;
        }

        return min(end, n);
    }
};
/* The read4 API is defined in the parent class Reader4.
      int read4(char[] buf); */

public class Solution extends Reader4 {
    /**
     * @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) {
        int end = 0; char[]tmp = new char[4];
        while(end < n){
            int count = read4(tmp);
            int stop = Math.min(end + count, n);
            for (int i = end; i < stop; i++)
                buf[i] = tmp[i - end];
            end = stop;
            if(count < 4) return end;
        }

        return end;
    }
}

results matching ""

    No results matching ""