题意:

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. public $pointer = 0;
  10. public $len = 0;
  11. public $tmp = [];
  12. function read(&$buf, $n) {
  13. $index = 0;
  14. while ($index < $n) {
  15. if ($this->pointer == 0) {
  16. $this->len = $this->read4($this->tmp);
  17. }
  18. if ($this->len == 0) break;
  19. while ($index < $n && $this->pointer < $this->len) {
  20. $buf[$index++] = $this->tmp[$this->pointer++];
  21. }
  22. // 说明临时字符数组中的内容已经读完,pointer置零以便执行下一次read4操作
  23. if ($this->pointer >= $this->len) $this->pointer = 0;
  24. }
  25. return $index;
  26. }
  27. }

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. tmp := make([]byte, 4)
  16. pointer, len := 0, 0
  17. return func(buf []byte, n int) int {
  18. index := 0
  19. for index < n {
  20. if pointer == 0 {
  21. len = read4(tmp)
  22. }
  23. if len == 0 {
  24. break
  25. }
  26. for index < n && pointer < len {
  27. buf[index] = tmp[pointer]
  28. index++
  29. pointer++
  30. }
  31. if pointer >= len {
  32. pointer = 0
  33. }
  34. }
  35. return index
  36. }
  37. }