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 functionint read(char *buf, int n)
that reads n characters from the file.函數Note:
Theread
function will only be called once for each test case.spa
這道題沒什麼特殊的算法跟數據結構,注意越界就能夠了。至於越界主要包含兩種狀況,一是讀到文件結尾,沒得讀了。而是還沒讀到文件結尾,可是已經達到要求的n個字符了,此時應該中止繼續讀。處理好這兩種狀況便可。code
這道題Follow up能夠是屢次讀,也是LeetCode原題,即
Read N Characters Given Read4 II - Call multiple times
, 具體見後文。ip
time: O(n), space: O(1)it
/* 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 i = 0; char[] buffer = new char[4]; while (i < n) { int bufCount = read4(buffer); int j = 0; while (j < bufCount && i < n) { buf[i++] = buffer[j++]; } if (bufCount != 4) break; } return i; } }
The API:
int read4(char *buf)
reads 4 characters at a time from a file.ioThe return value is the actual number of characters read. For example, it returns 3 if there is only 3 characters left in the file.function
By using the
read4
API, implement the functionint read(char *buf, int n)
that reads n characters from the file.classNote:
Theread
function may be called multiple times.
屢次讀與一次讀的主要不一樣在於read4()
函數中的buffer至關於global的,每次read()
的時候前面read4()
裏讀進buffer的剩下來字符的還要繼續用,不夠才又調用read4()
往buffer裏新增長內容供read
讀取。
因此咱們只要存一個global的針對read4()
的buffer的起始位置和終止位置便可。每次read()
先讀上次buffer裏沒讀完的字符,不夠才又調用read4()
. 固然,越界問題仍是得注意,跟上一道題同樣。
time: O(n), space: O(1)
/* The read4 API is defined in the parent class Reader4. int read4(char[] buf); */ public class Solution extends Reader4 { char[] buffer = new char[4]; int start = 0; // inclusive int end = 0; // exclusive /** *@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 i = 0; while (i < n) { // 以前read4()讀進buffer裏的字符已所有讀完 if (start == end) { end = read4(buffer); start = 0; } // 依次把buffer裏的字符讀進buf裏 while (i < n && start < end) { buf[i++] = buffer[start++]; } // 判斷是否到達文件末尾,是的話跳出循環 if (end != 4) break; } return i; } }