题意:

image.png
image.png

解题思路:

  1. 思路:
  2. 1. 循环读,循环条件判断长度是否到了n

PHP代码实现:

  1. /* The read4 API is defined in the parent class Reader4.
  2. public function read4(&$buf){} */
  3. class Solution extends Reader4 {
  4. /**
  5. * @param Char[] &$buf Destination buffer
  6. * @param Integer $n Number of characters to read
  7. * @return Integer The number of actual characters read
  8. */
  9. //file-> read4 -> 4个一组,每组读完放到buf里面-> 读到n个结果,返回个数
  10. function read(&$buf, $n) {
  11. //临时存放read4结果的数组
  12. $tmp = [];
  13. //定义tmp指针
  14. $index = 0;
  15. //4个一组,每组读完放到buf里
  16. while ($index < $n) {//没有读够n个字符
  17. //当前读到的长度
  18. $len = $this->read4($tmp);
  19. //pointer是tmp里面的index
  20. $pointer = 0;
  21. //把tmp读到的临时数据放到buf里;
  22. //buf里的数量不足n,pointer的位置没有到len
  23. while ($index < $n && $pointer < $len) {
  24. $buf[$index] = $tmp[$pointer];
  25. $index++;
  26. $pointer++;
  27. }
  28. //已经读完file.ex filr "abcde", n = 6
  29. if ($len < 4) break;
  30. }
  31. return $index;
  32. }
  33. }

GO代码实现:

  1. /**
  2. * The read4 API is already defined for you.
  3. *
  4. * read4 := func(buf []byte) int
  5. *
  6. * // Below is an example of how the read4 API can be called.
  7. * file := File("abcdefghijk") // File is "abcdefghijk", initially file pointer (fp) points to 'a'
  8. * buf := make([]byte, 4) // Create buffer with enough space to store characters
  9. * read4(buf) // read4 returns 4. Now buf = ['a','b','c','d'], fp points to 'e'
  10. * read4(buf) // read4 returns 4. Now buf = ['e','f','g','h'], fp points to 'i'
  11. * read4(buf) // read4 returns 3. Now buf = ['i','j','k',...], fp points to end of file
  12. */
  13. var solution = func(read4 func([]byte) int) func([]byte, int) int {
  14. // implement read below.
  15. return func(buf []byte, n int) int {
  16. tmp := make([]byte, 4)
  17. index := 0
  18. for index < n {
  19. len := read4(tmp)
  20. pointer := 0
  21. for index < n && pointer < len {
  22. buf[index] = tmp[pointer]
  23. index++
  24. pointer++
  25. }
  26. if len < 4 {
  27. break
  28. }
  29. }
  30. return index
  31. }
  32. }