[英]The code is working properly but I am not able to solve all test cases in python
Given a stack of integers, write a python program that updates the input stack such that all occurrences of the smallest values are at the bottom of the stack, while the order of the other elements remains the same. 给定一个整数堆栈,编写一个python程序来更新输入堆栈,以使所有出现的最小值都在堆栈的底部,而其他元素的顺序保持不变。
For example: 例如:
Input stack (top-bottom) : 5 66 5 8 7
Output: 66 8 7 5 5
def change_smallest_value(number_stack):
#write your logic here
size = number_stack.get_max_size()
li = []
for i in range(size):
a = number_stack.pop()
if (a != None):
li.append(a)
li.sort()
for i in li:
number_stack.push(i)
return number_stack
5 out of 8 test cases passed. 8个测试用例中有5个通过了。
You do not show us the code for your stack, which makes it hard for us to test. 您没有向我们显示堆栈的代码,这使我们难以测试。 But here is an algorithm in pseudocode--I'll let you fill in the code. 但是这是伪代码中的一种算法-我让您填写代码。
Create a new, empty stack
Set the minimum-value-so-far to something ridiculously large
while the old stack is not empty:
Pop one value off the old stack
if that value is smaller than the minimum-value-so-far:
Set the minimum-value-so-far to the current value
Set the frequency of that minimum to one
else if that value equals the minimum-value-so-far:
Increase the frequency of that minimum by one
Push that value onto the new stack
Push the minimum value onto the old stack, the frequency number of times
while the new stack is not empty:
Pop one value off the new stack
if that value does not equal the minimum value:
Push that value onto the old stack
Return the old (modified) stack
This uses an extra stack, but at no time does any item exist in both stacks simultaneously, so the memory usage of this code is O(1). 这会使用一个额外的堆栈,但是两个堆栈中都不会同时存在任何项,因此此代码的内存使用量为O(1)。 The execution time is O(n) where n
is the size of the stack--each item is seen twice. 执行时间为O(n),其中n
是堆栈的大小-每个项目被看到两次。 Moving items between two stacks twice inverts the order the first time and restores the order the second time--except for the special value (the minimum) that is handled differently. 在两个堆栈之间移动项目两次会第一次反转顺序,第二次还原顺序-特殊值(最小值)的处理方式有所不同。
li.sort()
will breaks the order of your stack. li.sort()
将破坏堆栈的顺序。 remove the line 删除线
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.