avatar
CareerCup question# JobHunting - 待字闺中
c*e
1
3.2 How would you design a stack which, in addition to push and pop, also
has a function min which returns the minimum element? Push, pop and min
should all operate in O(1) time.
I do not think it possible. The answer given seems wrong. Any comment?
Thanks.
avatar
S*w
2
用数组做?

【在 c**********e 的大作中提到】
: 3.2 How would you design a stack which, in addition to push and pop, also
: has a function min which returns the minimum element? Push, pop and min
: should all operate in O(1) time.
: I do not think it possible. The answer given seems wrong. Any comment?
: Thanks.

avatar
q*c
3
Use linked list for the stack. Push and pop would be O(1). Also update the
min value on every push then you can get MinVal in O(1). In the case that
you pop the min, scan the list to find the min and that would take O(n), but
it's not included in the MinVal operation so MinVal still takes O(1).
avatar
c*e
4
Then pop() is not O(1). Did I miss anything?

but

【在 q********c 的大作中提到】
: Use linked list for the stack. Push and pop would be O(1). Also update the
: min value on every push then you can get MinVal in O(1). In the case that
: you pop the min, scan the list to find the min and that would take O(n), but
: it's not included in the MinVal operation so MinVal still takes O(1).

avatar
q*c
5
Pop is still O(1) since you only get the head node from the list.Updating
min is not included in Pop. That's my understanding.
avatar
k*t
6
Use two stacks internally.

【在 c**********e 的大作中提到】
: 3.2 How would you design a stack which, in addition to push and pop, also
: has a function min which returns the minimum element? Push, pop and min
: should all operate in O(1) time.
: I do not think it possible. The answer given seems wrong. Any comment?
: Thanks.

avatar
H*e
7
如果想好解释的话,就把stack中的数据增加一个field,用来存迄今为止最小的
这样每次pop也就可以看到了

【在 k***t 的大作中提到】
: Use two stacks internally.
avatar
r*t
8
i think the answer is correct, it is not O(1) space, but it is O(1) time.

【在 c**********e 的大作中提到】
: 3.2 How would you design a stack which, in addition to push and pop, also
: has a function min which returns the minimum element? Push, pop and min
: should all operate in O(1) time.
: I do not think it possible. The answer given seems wrong. Any comment?
: Thanks.

avatar
x*3
9
Correct. Just find a way to store the min element corresponding to current
element.

【在 H***e 的大作中提到】
: 如果想好解释的话,就把stack中的数据增加一个field,用来存迄今为止最小的
: 这样每次pop也就可以看到了

avatar
c*e
10
Thank you guys. It is clear to me now.
相关阅读
logo
联系我们隐私协议©2024 redian.news
Redian新闻
Redian.news刊载任何文章,不代表同意其说法或描述,仅为提供更多信息,也不构成任何建议。文章信息的合法性及真实性由其作者负责,与Redian.news及其运营公司无关。欢迎投稿,如发现稿件侵权,或作者不愿在本网发表文章,请版权拥有者通知本网处理。