[Leetcode] 158. Read N Characters Given Read4 II
来源:互联网 发布:汽车零部件进出口数据 编辑:程序博客网 时间:2024/05/22 07:55
题目:
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.
思路:
建议读者将这道题目和Leetcode 157结合起来思考。它和Leetcode 157的不同之处就在于read(char *buf, int n)方法可能被调用多次,这样就产生了一个问题:上一次调用时读到buffer中的内容可能没有被取尽,所以下次调用read方法时,需要优先从上次没有读完的buffer中读取数据。所以,我们需要在类中记录三个类变量:长度为4的缓冲区(buffer),有效长度(last_length)以及起始位置(last_pos)。每次在调用read(char *buf, int n)的时候,我们首先从buffer中读取剩余数据;然后再调用read4这一API从文件中读取数据(这一部分的思路就和Leetcode 157完全一样了)。
代码:
// Forward declaration of the read4 API.int read4(char *buf);class Solution {public: /** * @param buf Destination buffer * @param n Maximum number of characters to read * @return The number of characters read */ int read(char *buf, int n) { int ret = 0; while(last_pos < last_length && n-- > 0) { // read the left charachters from last time buf[ret++] = buffer[last_pos++]; } while(n > 0) { last_length = read4(buffer); if(last_length == 0) { return ret; } last_pos = 0; while(last_pos < last_length && n-- > 0) { // read the current chacters until read over or the read length reaches n buf[ret++] = buffer[last_pos++]; } } return ret; }private: int last_pos = 0, last_length = 0; char buffer[4];};
- [Leetcode] 158. Read N Characters Given Read4 II
- LeetCode - Read N Characters Given Read4 I && II
- LeetCode - Read N Characters Given Read4 II - Call multiple times
- Leetcode 158 Read N Characters Given Read4 II
- leetcode Read N Characters Given Read4
- leetcode 157: Read N Characters Given Read4
- [LeetCode] Read N Characters Given Read4
- Leetcode: Read N Characters Given Read4
- *LeetCode-Read N Characters Given Read4
- [leetcode 157] Read N Characters Given Read4
- [LeetCode] 157. Read N Characters Given Read4
- LeetCode 157: Read N Characters Given Read4
- LeetCode 157. Read N Characters Given Read4
- Leetcode 157 Read N Characters Given Read4
- [LeetCode] 158. Read N Characters Given Read4 II - Call multiple times
- [leetcode] 158. Read N Characters Given Read4 II - Call multiple times 解题报告
- LeetCode 158. Read N Characters Given Read4 II - Call multiple times(读文件流)
- Read N Characters Given Read4
- 系统和进程相关信息
- Balanced Lineup
- Linux的cat命令详解
- POJ 3041 Asteroids 匈牙利算法
- IE和DOM事件流的区别
- [Leetcode] 158. Read N Characters Given Read4 II
- C++数组指针
- android 通知栏的Intent事件
- 用友U8获取指定用户在某个账套中是否拥有指定权限
- java做网站
- LeetCode 561. Array Partition I
- 【数组模拟链表】UVA
- Spring线程池和自定义线程池的使用
- 06-图1 列出连通集 (25分) C++