本文介绍了在O(1)时间复杂度的堆栈中查找最小值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在O(1)复杂度的堆栈中找到最小值。为了找到堆栈的最小值,我找到了两种方法:

1)min =堆栈的最高值

遍历堆栈并更新最小值以获得堆栈的最小值。

这需要O(N)复杂度,其中N是堆栈中元素的数量



2)将堆栈元素放在minheap中

将提取的根值将是堆栈中的最小值

这需要O(N log(N))



但是如何实现O(1)算法,一种独立于输入大小的算法。



这里的假设是堆栈已经加载了元素



另一个问题是数据结构在C或java中是否有效?因为在C中我们手动使用指针来分配内存.Java具有内置实现,以及实现它们的引用对象?哪一个要用?解决方案


How to find the minimum value in a stack with O(1) complexity.To find minimum value of a stack I found two ways :
1) min = top value of the stack
Traverse the stack and update the min value to get the minimum value of the stack.
This requires O(N) complexity where N is the number of elements in the stack

2) Put the stack elements in a minheap
The root value that will be extracted will be the minimum value in the stack
This requires O(N log(N))

But how do I implement O(1) algorithm , an Algorithm that is Independent of the Input size.

Here the assumption is that the stack is already loaded with elements

Another question is that data structures is efficient in C or java?Because in C we manually use pointers to allocate memory.Java has in-build implementation , as well as reference objects to implement them?Which one to go for?

解决方案


这篇关于在O(1)时间复杂度的堆栈中查找最小值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-22 13:30