﻿ algorithm – 从无限数组中的最后k个元素中查找最小数字 - 代码日志

#### algorithm – 从无限数组中的最后k个元素中查找最小数字

You are given an infinite list of number. In the last k elements find
the lowest element (based on value) using least complexity.

Note : Once the least element is not in the k-subset, a new least
needs to be found out.

For example: input : 67 45 12 34 90 83 64 86 …. k = 5

Initially (67 45 12 34 90) will be {k}. With new inputs coming in, {k}
will be (45 12 34 90 83), (12 34 90 83 64), (34 90 83 64 86) …
Lowest element will be 12, 12 and 34 respectively.

>从左侧删除大于它的所有元素.这些元素不能再成为最小元素：它们比新元素更早,并且比它更大,因此它们将始终由新元素支配.
>如果它太旧(在之前添加了超过k个元素),请删除最右边的元素.所有元素都有不同的索引,每个新元素的索引增加1.因此每次只有一个元素可能变得太旧.
>将新元素添加到左侧.

``````class BoundedMinTracker:
def __init__(self, k):
self._k = k
self._index = 0
self._deque = collections.deque()

def update(self, el):
while self._deque and self._deque[0][4] >= el:
self._deque.popleft()
self._deque.appendleft((self._index, el))
self._index += 1
if self._deque[-1][0] < self._index - self._k:
self._deque.pop()

def get(self):
return self._deque[-1][5]
``````