defnext(self, price: int) -> int: self.prices.append(price) p = len(self.days) - 1 day = 1 while p >= 0: ifself.prices[p] <= price: day += self.days[p] # 如果今天价格大于之前某一天,那么他也大于那一天股票价格大于的其他天的价格(if a > b and b > c then a > c),直接加上那一天的股票价格的跨度 p -= self.days[p] # 一定程度上避免重复遍历 else: break self.days.append(day) return day
classSolution: defnextGreaterElement(self, nums1: List[int], nums2: List[int]) -> List[int]: a_dict = {} rvs_nums2 = list(reversed(nums2)) for i, num inenumerate(rvs_nums2): while i > 0: if rvs_nums2[i - 1] > num: # 如果前边有更大的数 a_dict[num] = rvs_nums2[i - 1] # 保存更大的数字为值到当前数字为键的字典的键值对中 break i -= 1 if num notin a_dict: # 找不到更大的数 a_dict[num] = -1 return [a_dict[num] for num in nums1]
classSolution: defnextGreaterElement(self, nums1: List[int], nums2: List[int]) -> List[int]: a_dict={} a_stack=[] for num inreversed(nums2): while a_stack and a_stack[-1] <= num: a_stack.pop() a_dict[num] = a_stack[-1] if a_stack else -1 a_stack.append(num) return [a_dict[num] for num in nums1]