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; } }