LeetCode Read N Characters Given Read4 II - Call multiple times

时间:2021-12-22 15:11:50

原题链接在这里:https://leetcode.com/problems/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.

题解:

需要多次调用,用queue来保存前一次调用read4没用完的数据.

read时先用queue中的数据添加到buf中,若是不够再call read4.

在读够n个char后若是read4Buff中还有可用数据,加到queue中.

Note: declear rest first, but not use i < n - readSum in the while condidtion since readSum is changing.

Time Complexity: read, O(n).

Space: O(1). queue的大小不会超过4.

AC Java:

 /**
* The read4 API is defined in the parent class Reader4.
* int read4(char[] buf);
*/
public class Solution extends Reader4 {
LinkedList<Character> que = new LinkedList<>(); /**
* @param buf Destination buffer
* @param n Number of characters to read
* @return The number of actual characters read
*/
public int read(char[] buf, int n) {
int readSum = 0;
// 先用queue中剩余的上次结果加到buf中
while(readSum < n && !que.isEmpty()){
buf[readSum++] = que.poll();
} // 若是不够再调用read4 API
boolean eof = false;
char [] temp = new char[4];
while(!eof && readSum < n){
int count = read4(temp);
eof = count < 4;
int rest = n-readSum; int i = 0;
while(i < count && i < rest){
buf[readSum++] = temp[i++];
} // 把当前read4Buff中没有读的有用char加到queue中
if(i == rest){
while(i < count){
que.add(temp[i++]);
}
}
} return readSum;
}
}

类似Read N Characters Given Read4.