LeetCode 158. 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:

 1 /**
 2  * The read4 API is defined in the parent class Reader4.
 3  *     int read4(char[] buf); 
 4  */
 5 public class Solution extends Reader4 {
 6     LinkedList<Character> que = new LinkedList<>();
 7     
 8     /**
 9      * @param buf Destination buffer
10      * @param n   Number of characters to read
11      * @return    The number of actual characters read
12      */
13     public int read(char[] buf, int n) {
14         int readSum = 0;
15         // 先用queue中剩余的上次结果加到buf中
16         while(readSum < n && !que.isEmpty()){
17             buf[readSum++] = que.poll();
18         }
19         
20         // 若是不够再调用read4 API
21         boolean eof = false;
22         char [] temp = new char[4];
23         while(!eof && readSum < n){
24             int count = read4(temp);
25             eof = count < 4;
26             int rest = n-readSum;
27             
28             int i = 0;
29             while(i < count && i < rest){
30                 buf[readSum++] = temp[i++];
31             }
32             
33             // 把当前read4Buff中没有读的有用char加到queue中
34             if(i == rest){
35                 while(i < count){
36                     que.add(temp[i++]);
37                 }
38             }
39         }
40         
41         return readSum;
42     }
43 }

类似Read N Characters Given Read4

posted @ 2016-03-26 05:03  Dylan_Java_NYC  阅读(404)  评论(0编辑  收藏  举报