原题链接在这里: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.

最新文章

  1. htmlentities,html_entity_decode,addslashes
  2. 自动化小应用系列----利用selenium启动多个独立的浏览器
  3. [AIR] 打开我的电脑
  4. SQL Server日期时间格式转换字符串
  5. 转 浅谈算法和数据结构: 十 平衡查找树之B树
  6. 简答哈希实现 (nyoj 138 找球号2)
  7. Android 屏幕适配(一)百分比布局库(percent-support-lib) 解析与扩展
  8. PDO 学习与使用 ( 二 ) PDO 数据提取 和 预处理语句
  9. Spring MVC BeanNameUrlHandlerMapping example
  10. OpenCms Application dev-ref
  11. android手机内存大小获取
  12. 二叉树,AVL树和红黑树
  13. 区块链名词解析:ICO、IFO、IEO和IMO,分别是什么呢?
  14. Linux安装 火速入门
  15. iOS UI进阶-1.1 Quartz2D 图片水印/裁剪/截图
  16. gaea-editor 知识点
  17. redis 集群目标、集群查看、配置方法及过程、哨兵配置启动
  18. 开始SDK之旅-入门2-集成流程图、轨迹图到系统
  19. 转:Entity FrameWork利用Database.SqlQuery&lt;T&gt;执行存储过程并返回参数
  20. iOS UITableView划动删除的实现

热门文章

  1. 【Linux程序设计】之进程控制&amp;守护进程
  2. 怎样测试TCP&amp;UDP端口
  3. UVa 11388 &amp; 丝帛
  4. BZOJ3212 Pku3468 A Simple Problem with Integers 题解
  5. iOS 上线被拒收集
  6. WinForm 快捷键设置(转载)
  7. Hashtable在ViewState中无法增加值
  8. 详解CALayer 和 UIView的区别和联系
  9. JavaScript实现省市级联效果实例
  10. 【HDU 4747 Mex】线段数