← 返回 reddit 的题目列表Implement an In-Memory Chatter Message Store
类型:online_judge
Implement an in-memory Chatter message store. Each message has a unique chat_msg_id and text. Messages are loaded in batches via load; there are no duplicate IDs, and arrival order is ascending by chat_msg_id.
Implement:
class Chatter:
def load(self, messages):
"""Append a batch of new messages. May be called multiple times."""
def save(self):
"""Return all currently stored messages in message order."""
def get_messages(self, msg_id):
"""Return the target message, up to two preceding messages, and up to
two following messages, ordered by chat_msg_id.
"""
def get_multi(self, ids):
"""Run get_messages for every requested ID, merge the results, sort by
chat_msg_id, and remove duplicate messages.
"""
def edit(self, msg_id, message):
"""Update the text of the message identified by msg_id."""
Example
chat_messages_1 = [
{"chat_msg_id": 123.41, "message": "Hello Snoo"},
{"chat_msg_id": 123.43, "message": "Very nice to meet"},
{"chat_msg_id": 123.45, "message": "you."},
{"chat_msg_id": 123.47, "message": "Hope you had a wonderful"},
{"chat_msg_id": 124.48, "message": "time so far."},
]
chatter = Chatter()
chatter.load(chat_messages_1)
chatter.get_messages(123.41)
Expected result:
[
{"chat_msg_id": 123.41, "message": "Hello Snoo"},
{"chat_msg_id": 123.43, "message": "Very nice to meet"},
{"chat_msg_id": 123.45, "message": "you."},
]
Requirements
Let n be the number of loaded messages. Make a single get_messages query as efficient as possible.
The system receives many get_messages and get_multi reads. Describe and implement an appropriate index or cache.
After edit, subsequent calls to save, get_messages, and get_multi must expose the updated message content.
If an ID does not exist, return an empty list.
Example
Input
load([{1:'a'}, {2:'b'}, {3:'c'}]); get_messages(1)
Output
[{1:'a'}, {2:'b'}, {3:'c'}]