您可以使用stacks 中的dynamic array,与hash table 结合使用。
数组每个频率都有一个条目,因此第一次出现的所有 N 值将存储在第一个数组条目中,第二次出现的 N 值将存储在第二个数组条目中,.. 。ETC。在每个数组条目中,收集到的 N 个值将按查询顺序存储 - 即作为堆栈。当一个 N 值重复出现时,它们之前的位置不会受到影响……另一个 N 值只会被添加到另一个堆栈中。
哈希表将用于跟踪 N 值的当前出现次数。它的键/值对是(N,频率)对。这样我们就知道在哪个子栈中找到/添加某个 N。
伪代码中的算法:
function solve(queries)
array ← an empty dynamic array of stacks of N-values
freq ← an empty hashmap of (N, frequency) key/value pairs
result ← an empty dynamic array of N-values
for i ← 1 to length(queries) do
x ← queries[i][1]
n ← queries[i][2]
if x equals 1 then
if not freq has n then
freq[n] ← 0
end if
increment freq[n]
if freq[n] > size of array then
append an emtpy stack to array
end if
push n on the stack at array[freq[n]]
else
stack ← last stack on array
pop n from stack
if stack is empty then
pop this stack from array
end if
append n to result
end if
end for
return result
end function
在 Python 中的实现:
def solve(queries):
buckets = [[-1]] # entry at index 0 is not used. It is just a filler
freq = defaultdict(int)
for i, (x, n) in enumerate(queries):
if x == 1:
freq[n] += 1
if freq[n] >= len(buckets):
buckets.append([])
buckets[freq[n]].append(n)
else:
n = buckets[-1].pop()
if len(buckets[-1]) == 0:
buckets.pop()
yield n
# Demo run
queries = [(1, 2),(1, 4),(1, 3),(1, 2),(2, -1),(2, -1)]
print(*solve(queries))