LeetCode Read N Characters Given Read4 II - Call multiple times
原题链接在这里:https://leetcode.com/problems/read-n-characters-given-read4-ii-call-multiple-times/
题目:
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.
题解:
需要多次调用,用queue来保存前一次调用read4没用完的数据.
read时先用queue中的数据添加到buf中,若是不够再call read4.
在读够n个char后若是read4Buff中还有可用数据,加到queue中.
Note: declear rest first, but not use i < n - readSum in the while condidtion since readSum is changing.
Time Complexity: read, O(n).
Space: O(1). queue的大小不会超过4.
AC Java:
/**
* The read4 API is defined in the parent class Reader4.
* int read4(char[] buf);
*/
public class Solution extends Reader4 {
LinkedList<Character> que = new LinkedList<>(); /**
* @param buf Destination buffer
* @param n Number of characters to read
* @return The number of actual characters read
*/
public int read(char[] buf, int n) {
int readSum = 0;
// 先用queue中剩余的上次结果加到buf中
while(readSum < n && !que.isEmpty()){
buf[readSum++] = que.poll();
} // 若是不够再调用read4 API
boolean eof = false;
char [] temp = new char[4];
while(!eof && readSum < n){
int count = read4(temp);
eof = count < 4;
int rest = n-readSum; int i = 0;
while(i < count && i < rest){
buf[readSum++] = temp[i++];
} // 把当前read4Buff中没有读的有用char加到queue中
if(i == rest){
while(i < count){
que.add(temp[i++]);
}
}
} return readSum;
}
}
类似Read N Characters Given Read4.
最新文章
- htmlentities,html_entity_decode,addslashes
- 自动化小应用系列----利用selenium启动多个独立的浏览器
- [AIR] 打开我的电脑
- SQL Server日期时间格式转换字符串
- 转 浅谈算法和数据结构: 十 平衡查找树之B树
- 简答哈希实现 (nyoj 138 找球号2)
- Android 屏幕适配(一)百分比布局库(percent-support-lib) 解析与扩展
- PDO 学习与使用 ( 二 ) PDO 数据提取 和 预处理语句
- Spring MVC BeanNameUrlHandlerMapping example
- OpenCms Application dev-ref
- android手机内存大小获取
- 二叉树,AVL树和红黑树
- 区块链名词解析:ICO、IFO、IEO和IMO,分别是什么呢?
- Linux安装 火速入门
- iOS UI进阶-1.1 Quartz2D 图片水印/裁剪/截图
- gaea-editor 知识点
- redis 集群目标、集群查看、配置方法及过程、哨兵配置启动
- 开始SDK之旅-入门2-集成流程图、轨迹图到系统
- 转:Entity FrameWork利用Database.SqlQuery<;T>;执行存储过程并返回参数
- iOS UITableView划动删除的实现