157.Read N Characters Given Read4
Tags: [file], [file_system], [queue]
Com: {fb}
Link: https://leetcode.com/problems/read-n-characters-given-read4/\#/description
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 theread4
API, implement the functionint read(char *buf, int n)
that readsncharacters from the file.
Note:
The read
function will only be called once for each test case.
Solution: Queue
# The read4 API is already defined for you.
# @param buf, a list of characters
# @return an integer
# def read4(buf):
from collections import deque
class Solution(object):
def read(self, buf, n):
"""
:type buf: Destination buffer (List[str])
:type n: Maximum number of characters to read (int)
:rtype: The number of characters read (int)
"""
if not n:
return 0
queue = deque()
while len(queue) < n:
sub_buf = ['' for _ in xrange(4)]
num_of_chars = read4(sub_buf)
if not num_of_chars:
break
for i in xrange(num_of_chars):
queue.append(sub_buf[i])
index = 0
while index < n and queue:
buf[index] = queue.popleft()
index += 1
return index
Revelation:
- Do not forget to check whether num__of__chars is 0 during the first while loop.
Another Solution:
# The read4 API is already defined for you.
# @param buf, a list of characters
# @return an integer
# def read4(buf):
class Solution(object):
def read(self, buf, n):
"""
:type buf: Destination buffer (List[str])
:type n: Maximum number of characters to read (int)
:rtype: The number of characters read (int)
"""
if not n:
return 0
index = 0
while n > 4:
sub_buf = ['' for _ in xrange(4)]
num_of_chars = read4(sub_buf)
if not num_of_chars:
break
for i in xrange(num_of_chars):
buf[index] = sub_buf[i]
index += 1
n -= num_of_chars
if n:
sub_buf = ['' for _ in xrange(4)]
num_of_chars = read4(sub_buf)
for i in xrange(min(n, num_of_chars)):
buf[index] = sub_buf[i]
index += 1
return index