[LeetCode 660] 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.

Example

Example 1

Input:
"filetestbuffer"
read(6)
read(5)
read(4)
read(3)
read(2)
read(1)
read(10)
Output:
6, buf = "filete"
5, buf = "stbuf"
3, buf = "fer"
0, buf = ""
0, buf = ""
0, buf = ""
0, buf = ""

Example 2

Input:
"abcdef"
read(1)
read(5)
Output:
1, buf = "a"
5, buf = "bcdef"

Notice

The read function may be called multiple times.

 

分析

这道题是一道非常经典的工程类的题目。在存储的设计实现中,为了提升性能,我们经常会将用户的读写请求按照固定的bufferSize下发下去,这样的话就涉及到用户的请求进行分片。也就是本题的考察问题,我们需要将用户的请求按照4Bytes分片读出。首先需要一个缓冲区来缓存4Bytes的内容,同时使用pos和remain来标记缓冲区目前指针的位置和剩余字节数,然后在处理用户请求时,如果用户需要的字节数n >= remain,首先copy缓冲区的剩余内容到buf,然后循环的按照4Byte读出并copy到buf,如果读不出内容则直接返回当前的total字节数。最后如果remain > n,说明此时缓冲区的内容可以直接copy需要的字节数到buf即可。

Code

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

class Solution {
public:

    Solution()
    {
        memset(buffer, 0, sizeof(buffer));
        remain = 0;
        pos = 0;
    }
    /**
     * @param buf destination buffer
     * @param n maximum number of characters to read
     * @return the number of characters read
     */
    int read(char *buf, int n) {
        // Write your code here
        int total = 0;
        while (remain <= n)
        {
            memcpy(buf + total, buffer + pos, remain);
            n = n - remain;
            total += remain;
            remain = read4(buffer);
            pos = 0;
            if (remain == 0)
                return total;
        }
        if (remain > n)
        {
            memcpy(buf + total, buffer + pos, n);
            total += n;
            remain -= n;
            pos += n;
        }
        
        return total;
    }
    
private:
    char buffer[4];
    int remain;
    int pos;
};

运行效率

Your submission beats 60.40% Submissions!

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值