【LeetCode】158. Read N Characters Given Read4 II - Call multiple times

32 篇文章 0 订阅
32 篇文章 0 订阅

LeetCode158 传送门

推荐解法:

    设置成员变量offset,长度为4的列表buffer,buffer中的字符串长度bufsize。在调用read时,先利用bufsize和offset判断buffer中是否存在尚未被输出的字符。如果存入buf中,判断buf中存储的字符串长度还未到达n或read4的指针还未来到终点,则循环调用read4将所需长度的字符串加入buf并重复上一个判断,直到条件不满足。

Python源码,来自ycsung

    该方法采用queue数据结构,简洁优雅地实现了read方法。赞。

class Solution(object):
    def __init__(self):
        self.queue = []
        
    def read(self, buf, n):
        """
        :type buf: Destination buffer (List[str])
        :type n: Number of characters to read (int)
        :rtype: The number of actual characters read (int)
        """
        idx = 0
        while True:
            buf4 = ['']*4
            l = read4(buf4)
            self.queue.extend(buf4)
            curr = min(len(self.queue), n-idx)
            for i in range(curr):
                buf[idx] = self.queue.pop(0)
                idx += 1
            if curr == 0:
                break
        return idx

我的心路:

    思路和推荐解法类似,但1个半小时也没能实现出来。(┬_┬)

    默写了一下上面的方法。

Runtime: 20 ms, faster than 58.10% of Python online submissions for Read N Characters Given Read4 II - Call multiple times.

Memory Usage: 11.9 MB, less than 100.00% of Python online submissions for Read N Characters Given Read4 II - Call multiple times.

class Solution(object):
    def __init__(self):
        self.queue = []
        
    def read(self, buf, n):
        """
        :type buf: Destination buffer (List[str])
        :type n: Number of characters to read (int)
        :rtype: The number of actual characters read (int)
        """
        idx = 0
        while True:
            buf4 = ['']*4
            l = read4(buf4)
            self.queue.extend(buf4[:l])
            curr = min(len(self.queue), n - idx)
            for i in range(curr):
                buf[idx] = self.queue.pop(0)
                idx += 1
            if curr == 0:
                return idx

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值