LeetCode 157. Read N Characters Given Read4

原题链接在这里:https://leetcode.com/problems/read-n-characters-given-read4/

题目:

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.

题解:

Given API read4, 一次最多可以read 4个char, 并把这些char保留在temp Buff中.

Ask to design another API, 能一次最多读n个char. 每次call read4, 若是返回小于4, 说明已经到了end of file, 下一次跳出while loop.

readCount计数当前共读了多少char, n-readCount就是还需要读多少个char.

Time Complexity: O(n). Space: O(1).

AC Java:

 1 /**
 2  * The read4 API is defined in the parent class Reader4.
 3  *     int read4(char[] buf4);
 4  */
 5 
 6 public class Solution extends Reader4 {
 7     /**
 8      * @param buf Destination buffer
 9      * @param n   Number of characters to read
10      * @return    The number of actual characters read
11      */
12     public int read(char[] buf, int n) {
13         int readSum = 0;
14         boolean eof = false;
15         char[] temp = new char[4];
16 
17         while(!eof && readSum < n){
18             int count = read4(temp);
19             eof = count < 4;
20             
21             int rest = n - readSum;
22             int i = 0;
23             while(i < count && i < rest){
24                 buf[readSum++] = temp[i++];
25             }
26         }
27 
28         return readSum;
29     }
30 }

跟上Read N Characters Given Read4 II - Call multiple times.

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