LeetCode Read N Characters Given Read4

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

题解:

给了一个API read4, 一次最多可以read 4个char, 并把这些char保留在read4Buff中.

要求设计一个API, 能一次最多读n个char. 每次call read4, 若是返回小于4, 说明已经到了end of file, 下一次跳出while loop.

readCount计数当前读了多少char, n-readCount就是还需要读多少个char.

取read4得返回值 read4Num 和 n-readCount中的小值 为 当前loop要读的char个数. 挨个读到buf中.

Time Complexity: O(n). Space: O(1).

AC Java:

 1 /* The read4 API is defined in the parent class Reader4.
 2       int read4(char[] buf); */
 3 
 4 public class Solution extends Reader4 {
 5     /**
 6      * @param buf Destination buffer
 7      * @param n   Maximum number of characters to read
 8      * @return    The number of characters read
 9      */
10     public int read(char[] buf, int n) {
11         boolean EOF = false;
12         int readCount = 0;
13         while(!EOF && readCount < n){
14             char [] read4Buff = new char[4]; //read4 API读的byte都存在read4Buff中
15             int read4Num = read4(read4Buff);
16             if(read4Num < 4){
17                 EOF = true;
18             }
19             int countToRead = Math.min(n-readCount, read4Num);
20             for(int i = 0; i<countToRead; i++){
21                 buf[readCount++] = read4Buff[i]; //把read4Buff中前 countToRead个byte copy到 buf中
22             }
23         }
24         return readCount;
25     }
26 }

跟上Read N Characters Given Read4 II - Call multiple times.

你可能感兴趣的:(LeetCode Read N Characters Given Read4)