Read N Characters Given Read4 II - Call multiple times

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

为了方便编码,用了deque,但时间复杂度竟然只beat了9% C++ user。用deque就不需要复杂的条件判断了。

// Forward declaration of the read4 API.
int read4(char *buf);

class Solution {
public:
    /**
     * @param buf Destination buffer
     * @param n   Maximum number of characters to read
     * @return    The number of characters read
     */
    int read(char *buf, int n) {
        char *curbuf=buf;
        int realn=0;
        while(realn<n && !dq.empty())
        {
            curbuf[realn++]=dq.front();
            dq.pop_front();
        }

        while(realn<n)
        {
            int curn=read4(tmpbuf);

            int i=0;
            while(realn<n && i<curn)
            {
                buf[realn++]=tmpbuf[i++];
            }

            while(i<curn)
            dq.push_back(tmpbuf[i++]);

            //need to handle no more read situation
            if(curn<4)break;
        }
        return realn;
    }

    deque<char> dq;
    char tmpbuf[4];
};

不用deque,每一步都模仿deque怎么实现的用大小为4的数组进行改进。

// Forward declaration of the read4 API.
int read4(char *buf);

class Solution {
public:
    /**
     * @param buf Destination buffer
     * @param n   Maximum number of characters to read
     * @return    The number of characters read
     */
    int read(char *buf, int n) {
        if(size==0 && isEnd)return 0;

        char *curbuf=buf;
        int realn=0;
        while(realn<n && size)
        {
            curbuf[realn++]=tmpbuf[left++];
            size--;
        }

        if(left==4)left=0;

        while(realn<n && !isEnd)
        {
            int curn=read4(tmpbuf);

            int i=0;
            while(realn<n && i<curn)
            {
                buf[realn++]=tmpbuf[i++];
            }

            if(i<curn)
            {
                left=i;
                size=curn-i;
            }

            //need to handle no more read situation
            if(curn<4)
            {
                isEnd=true;
                break;
            }
        }
        return realn;
    }

    int left=0,size=0;
    bool isEnd=false;
    char tmpbuf[4];
};

results matching ""

    No results matching ""