编程算法面试常考题答案汇总
Design a Stock Tracker
Coding Interview Question: Design a Stock Tracker
Design a stock tracker which have the following core functionalities:
- Can show the highest, lowest, most recent price of a stock.
- Can log an entry of (timestamp, price).
- Can drop the price previously associated with a given timestamp.
Solution
# 本代码来自 Techie科技求职,由 Techie Learning,Inc 原创
# - Techielearning.com 是来自硅谷的科技职业发展平台。
# - 本代码所属课程:<< Techie编程算法集训营 >>
# - 12周56+课时精品内容,精讲软件工程师编程算法面试核心知识体系。
# - 120道面试真题详解,27类常考题型剖析,1对1面试辅导与专业答疑。
# - 官方网站:https://www.techielearning.com/
# - 版权所有,禁止转发和分享
from sortedcontainers import SortedDict, SortedList
class StockTracker(object):
def __init__(self):
self._ts_to_price = SortedDict()
self._prices = SortedList()
def highestPrice(self):
return self._prices[-1]
def lowestPrice(self):
return self._prices[0]
def mostRecentPrice(self):
return self._ts_to_price.peekitem()[1]
def log(self, timestamp, price):
self._ts_to_price[timestamp] = price
self._prices.add(price)
def drop(self, timestamp):
old_price = self._ts_to_price.pop(timestamp)
self._prices.discard(old_price)
如果大家对题目代码有任何问题,欢迎扫描下方的二维码或者搜索 TonyCoding20 添加Techie教师团队微信。期待与同学们继续交流!