Shawngbk / Leecode

Questions of Leecode
0 stars 0 forks source link

157. Read N Characters Given Read4 #95

Open Shawngbk opened 7 years ago

Shawngbk commented 7 years ago

https://segmentfault.com/a/1190000003794420 复杂度 时间 O(N) 空间 O(1)

思路 用一个临时数组,存放每次read4读到字符,再用一个指针标记buf数组目前存储到的位置,然后将这个临时数组的内容存到buf相应的位置就行了。这里需要注意两个corner case:

如果本次读到多个字符,但是我们只需要其中一部分就能完成读取任务时,我们要拷贝的长度是本次读到的个数和剩余所需个数中较小的 如果read4没有读满4个,说明数据已经读完,这时候对于读到的数据长度,因为也可能存在我们只需要其中一部分的情况,所以要返回总所需长度和目前已经读到的长度的较小的

/* The read4 API is defined in the parent class Reader4. int read4(char[] buf); */

public class Solution extends Reader4 { /* * @param buf Destination buffer * @param n Maximum number of characters to read * @return The number of characters read / public int read(char[] buf, int n) { int count = 0; char[] temp = new char[4]; while(count < n) { int num = read4(temp); if(num == 0) break; int index = 0; while(index < num && count < n) { buf[count++] = temp[index++]; } } return count; } }

Shawngbk commented 7 years ago

FB