LeetCode – Refresh – Read N Characters Given Read4 II

本文介绍了一种使用队列来优化read4函数的方法,该方法能够有效地记录之前的字符并确保读取操作的高效执行。通过维护一个队列来缓存未使用的字符,可以减少不必要的读取调用,提高整体性能。

Since it need to record the previous chars, we just have to maintain a queue. Actually, the number of left chars are no larger than 4.

 

 1 // Forward declaration of the read4 API.
 2 int read4(char *buf);
 3 
 4 class Solution {
 5 private:
 6     queue<char> container;
 7 public:
 8     /**
 9      * @param buf Destination buffer
10      * @param n   Maximum number of characters to read
11      * @return    The number of characters read
12      */
13     int read(char *buf, int n) {
14         int len = 0, each = INT_MAX;
15         while (!container.empty()) {
16             *buf = container.front();
17             container.pop();
18             buf++;
19             len++;
20         }
21         while (len < n && (each = read4(buf))) {
22             len += each;
23             buf += each;
24         }
25         if (len >= n) {
26             for (int i = 0; i < len - n; i++) {
27                 container.push(buf[n-len+i]);
28             }
29             buf[n-len] = '\0';
30             len = n;
31         }
32         return len;
33     }
34 };

 

转载于:https://www.cnblogs.com/shuashuashua/p/4357405.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值