我有一个由重复元素组成的数组,例如
arr = [1, 2, 3, 0, 2, 1]
现在,我想以这样一种方式将元素存储在堆栈中,即堆栈的顶部总是给我一个重复的元素,它出现在后面所有其他重复的元素之前。例如
arr = [1, 2, 3, 0, 2, 1, 3]
stack = [3, 1, 2]
这里,1、2和3是重复元素,2出现在所有其他重复元素之前,这就是为什么它位于堆栈顶部,然后是1,它出现在3之前,最后是3
的另一个例子
arr = [1,2,0,2,3,0,1]
stack = [1, 0, 2]
您可以假设元素只重复两次。
您可以跟踪您添加到堆栈中的所有唯一元素:
arr = [1, 2, 0, 2, 3, 0, 1]
unique = []
stack = []
for a in arr:
if a not in unique:
unique.append(a)
else:
stack.insert(0, a)
print(stack)
输出:
[1, 0, 2]
我看到这样一个算法:
1. Find repeated elements
2. Iterate the initial list from the tail to the head
2.1. Check if an element is in the repeated elements list
2.1.1 If yes -> add this item to the new list
2.2 break when len(newlist) == len(repeated_list)