1 import bisect 2 class TweetCounts: 3 def __init__(self): 4 self.records = {} 5 6 def recordTweet(self, tweetName: str, time: int) -> None: 7 if tweetName not in self.records: 8 self.records[tweetName] = [time] 9 else: 10 bisect.insort(self.records[tweetName],time) 11 # self.records[tweetName].append(time) 12 13 def getTweetCountsPerFrequency(self, freq: str, tweetName: str, startTime: int, endTime: int) -> 'List[int]': 14 result = [] 15 # self.records[tweetName].sort() 16 if tweetName not in self.records: 17 return [] 18 else: 19 delta = 0 20 if freq == 'minute': 21 delta = 60 22 elif freq == 'hour': 23 delta = 60 * 60 24 else: 25 delta = 60 * 60 * 24 26 i = 0 27 I = (endTime - startTime) // delta + 1 28 while i < I: 29 start = startTime + delta * i 30 end = min(startTime + delta * (i + 1),endTime + 1) 31 left = bisect.bisect_left(self.records[tweetName], start) 32 right = bisect.bisect_left(self.records[tweetName], end) 33 count = right - left 34 result.append(count) 35 i += 1 36 return result
算法思路:二分查找。
在插入数据的时候,使用插入排序。
在计算区间内符合条件的数值个数的时候,使用两次二分查找。