[LeetCode] 157. Read N Characters Given Read4

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 the read4 API, implement the function int read(char *buf, int n) that reads n characters from the file.
Note:
The read function will only be called once for each test case.

Thought process:
Use a temporary buffer of size 4. Copy from the temporary buffer to buf based on n. Break out of the loop if I reached end of file.

Solution:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
/* 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) {
        char[] temp = new char[4];
        int total = 0;
        
        while (true) {
            int read = Math.min(n - total, read4(temp));
            if (read == 0) {
                break;
            }
            
            for (int i = 0; i < read; i++) {
                buf[total + i] = temp[i];
            }
            total += read;
        }
        return total;
    }
}

Time complexity: O(min(n, file)).

Comments

Popular posts from this blog

[LeetCode] 714. Best Time to Buy and Sell Stock with Transaction Fee

[LeetCode] 269. Alien Dictionary

[LeetCode] 631. Design Excel Sum Formula