[LeetCode] 158. Read N Characters Given Read4 II - Call Multiple Times

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 may be called multiple times.

Thought process:
This question is different from 157. Read N Characters Given Read4, because if the characters read by read4 is more than n, I must start from the unused extra characters in the temp buffer next time. So the idea is to make temp buffer an instance variable. Use a temp pointer and a temp count to keep track of where and how many to read from temp buffer.

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
28
29
30
31
32
33
34
/* The read4 API is defined in the parent class Reader4.
      int read4(char[] buf); */

public class Solution extends Reader4 {
    private char[] temp = new char[4];
    private int tempPointer = 0;
    private int tempCount = 0;
    
    /**
     * @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 pointer = 0;
        while (pointer < n) {
            if (tempPointer == 0) {
                tempCount = read4(temp);
            }
            if (tempCount == 0) {
                break;
            }
            while (pointer < n && tempPointer < tempCount) {
                buf[pointer] = temp[tempPointer];
                pointer++;
                tempPointer++;
            }
            if (tempPointer == tempCount) {
                tempPointer = 0;
            }
        }
        return pointer;
    }
}

Time complexity: O(min(n, remaining file)) for every call to read.

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