0%

read-n-characters-given-read4

Read N Characters Given Read4 – LeetCode 157

Problem

Description

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 will only be called once for each test case.

Answer

Original

Code

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
// Forward declaration of the read4 API.
int read4(char *buf);

class Solution {
public:
int read(char *buf, int n) {
int res = 0;
for (int i = 0; i <= n / 4; ++i) {
int cur = read4(buf + res);
if (cur == 0) break;
res += cur;
}
return min(res, n);
}
};

思路

简单的循环读取,如果提早结束了就判断并返回,在n不是4的倍数但文件大小大于n时会存在信息泄露的安全风险,不过胜在逻辑清晰。时间复杂度$O(n)$,空间复杂度$O(1)$。

Better

还没看到更好的思路。