码迷,mamicode.com
首页 > 其他好文 > 详细

Leetcode: Read N Characters Given Read4 II - Call multiple times

时间:2015-01-22 08:13:46      阅读:487      评论:0      收藏:0      [点我收藏+]

标签:

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.

Show Tags
Have you met this question in a real interview?

这道题跟I不一样在于,read函数可能多次调用,比如read(buf,23)之后又read(buf, 25), 第一次调用时的buffer还没用完,还剩一个char在buffer里,第二次拿出来接着用,这样才能保证接着上次读的地方继续往下读。

1. 所以应该设置这4个char的buffer为instance variable(实例变量),这样每次调用read函数后buffer还剩的元素可以被保存下来,供给下一次读取

2. 那么下一次调用read函数时候,怎么知道上一次buffer里面还剩不剩未读元素呢?我们有oneRead(一次读到buffer里的char数),actRead(实际被读取的char数),oneRead-actRead就是还剩在buffer里的char数。通常oneRead == actRead, 只有当n-haveRead < oneRead时,才不等,这就是上一次调用read结束的时候。所以只要调用read函数发现oneRead != 0 时,就说明上一次调用read还剩了元素在buffer里,先读完这个,再调用read4读新的。oneRead也需要是instance varaible

3. 还需要设置一个offset: Use to keep track of the offset index where the data begins in the nextread call. The buffer could be read partially (due to constraints of reading upto n bytes) and therefore leaving some data behind.

                      |<--buffer-->|   
    // |_________________________|
    // |<---offset---> |<----oneRead--->

上图所示为一次read最后的情况,offset部分其实就是actRead的部分,oneRead = oneRead - actRead, 就剩下了右边一部分在buffer里没有读,下一次read函数调用,发现oneRead>0, 说明上一次read还剩了一部分没有读

 1 /* The read4 API is defined in the parent class Reader4.
 2       int read4(char[] buf); */
 3 
 4 public class Solution extends Reader4 {
 5     /**
 6      * @param buf Destination buffer
 7      * @param n   Maximum number of characters to read
 8      * @return    The number of characters read
 9      */
10      private char buffer = new char[4];
11      private int oneRead = 0;
12      private int offset = 0;
13      
14      public int read(char[] buf, int n) {
15          boolean lessthan4 = false;
16          int haveRead = 0;
17          while (!lessthan4 && haveRead < n) {
18              if (oneRead == 0) {
19                  oneRead = read4(buffer);
20                  lessthan4 = oneRead < 4;
21              }
22              int actRead = Math.min(n-haveRead, oneRead);
23              for (int i=0; i<actRead; i++) {
24                  buf[haveRead+i] = buffer[offset+i];
25              }
26              oneRead -= actRead;
27              offset = (offset + actRead) % 4;
28              haveRead += actRead;
29          }
30          return haveRead;
31      }
32 }

 

Leetcode: Read N Characters Given Read4 II - Call multiple times

标签:

原文地址:http://www.cnblogs.com/EdwardLiu/p/4240616.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!