The API:int read4(char *buf)reads4characters 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 functionint read(char *buf, int n)that reads n characters from the file.

Notice

Thereadfunction may be called multiple times.

#模拟内存向硬盘读数据的过程

#需要将字符读进缓冲区,然后从缓冲区去内存

#因为字符需要按顺去读进内存,所以可以运用到队列这个数据结构

#如果用到队列,下一步就要想,何时出队,何时入队

#具体到这一题,可以如果队列为空,就出队, 如果队列不为空就入队

#用到了滚动数组实现队列的方法,这里的滚动有些特殊,因为入队的元素数量是定量的

"""
The read4 API is already defined for you.
@param buf a list of characters
@return an integer
you can call Reader.read4(buf)
"""


class Solution:

    # @param {char[]} buf destination buffer
    # @param {int} n maximum number of characters to read
    # @return {int} the number of characters read
    def __init__(self):
        self.buf_4, self.head, self.tail = [None] * 4, 0, 0
    def read(self, buf, n):
        # Write your code here
        i = 0
        while i < n:
            if self.head == self.tail: #this means the queue is empty
                self.head, self.tail = 0, Reader.read4(self.buf_4)
                if not self.tail:
                    break
            buf[i], i, self.head = self.buf_4[self.head], i + 1, self.head + 1

        return i

results matching ""

    No results matching ""