Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save aquawj/cb4c0729b973ebccd34e01027a4da06a to your computer and use it in GitHub Desktop.
Save aquawj/cb4c0729b973ebccd34e01027a4da06a to your computer and use it in GitHub Desktop.
/* The read4 API is defined in the parent class Reader4.
int read4(char[] buf); */
## Idea
* Based on 159
* Because of call multiple times, there are more corner cases
* First time we call, we need to save extra characters for next call
* In the while loop, if buffPointer reaches current buffCount, it will be set as zero to be ready to read new data.
public class Solution extends Reader4 {
/**
* @param buf Destination buffer
* @param n Maximum number of characters to read
* @return The number of characters read
*/
private int pointer = 0; // temp数组的下标
private int counter = 0; // temp中的元素个数
private char[] temp = new char[4]; //can be 4096 here in interview
//重点理解:temp数组:pointer的上界是counter; buf数组:index的上界是n
public int read(char[] buf, int n) {
int index = 0;// buf的下标,也就是我们所有已经读完的个数。index of buf, also means the total chars we have read
while (index < n) {//注意整个循环中index是持续增长的,没有清零过程,意味着新读入的字符一直往后加
if (pointer == 0) {//this means we should read new chars 该读新的了
counter = read4(temp);
}
if (counter == 0) {//if no more chars can be read (n > total chars in file) 没有可以读的了,break
break;
}
//buf和temp两数组中,指针都没到最后时,赋值。执行次数看这两边哪个距离小执行几次
while (index < n && pointer < counter) {//pointer < counter, not <= cuz counter is num of chars, not index
buf[index++] = temp[pointer++];//both pointers should be increased
}
//temp读完到头了,pointer清零
if (pointer == counter) {//if all chars in temp have been read, update the pointer to 0 (need read new chars)
pointer = 0;
}
}
return index;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment