这是我参与更文挑战的第9天,活动详情查看: 更文挑战
描述
There is a stream of n (idKey, value) pairs arriving in an arbitrary order, where idKey is an integer between 1 and n and value is a string. No two pairs have the same id.
Design a stream that returns the values in increasing order of their IDs by returning a chunk (list) of values after each insertion. The concatenation of all the chunks should result in a list of the sorted values.
Implement the OrderedStream class:
- OrderedStream(int n) Constructs the stream to take n values.
- String[] insert(int idKey, String value) Inserts the pair (idKey, value) into the stream, then returns the largest possible chunk of currently inserted values that appear next in the order.
Example 1:
Input
["OrderedStream", "insert", "insert", "insert", "insert", "insert"]
[[5], [3, "ccccc"], [1, "aaaaa"], [2, "bbbbb"], [5, "eeeee"], [4, "ddddd"]]
Output
[null, [], ["aaaaa"], ["bbbbb", "ccccc"], [], ["ddddd", "eeeee"]]
Explanation
// Note that the values ordered by ID is ["aaaaa", "bbbbb", "ccccc", "ddddd", "eeeee"].
OrderedStream os = new OrderedStream(5);
os.insert(3, "ccccc"); // Inserts (3, "ccccc"), returns [].
os.insert(1, "aaaaa"); // Inserts (1, "aaaaa"), returns ["aaaaa"].
os.insert(2, "bbbbb"); // Inserts (2, "bbbbb"), returns ["bbbbb", "ccccc"].
os.insert(5, "eeeee"); // Inserts (5, "eeeee"), returns [].
os.insert(4, "ddddd"); // Inserts (4, "ddddd"), returns ["ddddd", "eeeee"].
// Concatentating all the chunks returned:
// [] + ["aaaaa"] + ["bbbbb", "ccccc"] + [] + ["ddddd", "eeeee"] = ["aaaaa", "bbbbb", "ccccc", "ddddd", "eeeee"]
// The resulting order is the same as the order above.
Note:
1 <= n <= 1000
1 <= id <= n
value.length == 5
value consists only of lowercase letters.
Each call to insert will have a unique id.
Exactly n calls will be made to insert.
解析
根据题意(其实这个题我光看英文没懂,如果有强迫症的同学可以不做这题,看了其他高手的解释才明白,可能题目发生过变化,当然也可能是我的英文太渣,其实我就算做完都没明白这题目的意思)。
就是先初始化一个长度为 n 的列表,然后根据 insert 函数,将 value 填充到列表指定位置上,并且返回一个当前 pre 及其之后都不为空的相连的子列表。这个 pre 就是题目中没有找到的点,理解起来有点吃力。初始化的时候 pre 为 0 ,如果当前要插入的位置不是 pre ,那么直接返回空列表,否则就顺着 pre 往后找不为空的相连的子列表并且返回,并更新 pre 。
解答
class OrderedStream(object):
def __init__(self, n):
"""
:type n: int
"""
self.r = [None] * n
self.pre = 0
def insert(self, idKey, value):
"""
:type idKey: int
:type value: str
:rtype: List[str]
"""
self.r[idKey-1] = value
if self.pre == idKey-1:
tmp = self.pre
while tmp<len(self.r) and self.r[tmp]:
tmp+=1
self.pre = tmp
return self.r[idKey-1:self.pre]
return []
运行结果
Runtime: 192 ms, faster than 83.13% of Python online submissions for Design an Ordered Stream.
Memory Usage: 13.8 MB, less than 98.75% of Python online submissions for Design an Ordered Stream.
原题链接:leetcode.com/problems/de…
您的支持是我最大的动力