stack with min operation

本文介绍了一种特殊的栈结构,该栈除了基本的push和pop操作外,还额外提供了一个min函数用以返回栈内最小元素。这种特殊的数据结构在进行push、pop及min操作时均能保证O(1)的时间复杂度。通过维护每个节点的当前最小值,确保了在任何时候都能快速找到最小元素。
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.



public class StackWithMin extends Stack<NodeWithMin> {
public void push(int value) {
int newMin = Math.min(value, min());
super.push(new NodeWithMin(value, newMin));
}
}
public int min() {

if (this.isEmpty()) {

return Integer.MAX_VALUE;

} else {

return peek().min;

}
}
class NodeWithMin {
public int value;
public int min;
public NodeWithMin(int v, int min){
value = v;
this.min = min;
}
}

--------------------------------------------------------------------------- TypeError Traceback (most recent call last) Cell In[19], line 18 15 bic_matrix.append(tmp) 17 bic_matrix = pd.DataFrame(bic_matrix) # 从中可以找出最小值 ---> 18 p,q = bic_matrix.stack().idxmin() # 先用stack展平,然后用idxmin找出最小值位置。 19 print(bic_matrix) 20 print('BIC最小的p值和q值为:',(p,q)) File D:\Anaconda3\envs\tf_2.0\lib\site-packages\pandas\core\series.py:2460, in Series.idxmin(self, axis, skipna, *args, **kwargs) 2396 """ 2397 Return the row label of the minimum value. 2398 (...) 2456 nan 2457 """ 2458 # error: Argument 1 to "argmin" of "IndexOpsMixin" has incompatible type "Union 2459 # [int, Literal['index', 'columns']]"; expected "Optional[int]" -> 2460 i = self.argmin(axis, skipna, *args, **kwargs) # type: ignore[arg-type] 2461 if i == -1: 2462 return np.nan File D:\Anaconda3\envs\tf_2.0\lib\site-packages\pandas\core\base.py:742, in IndexOpsMixin.argmin(self, axis, skipna, *args, **kwargs) 738 return delegate.argmin() 739 else: 740 # error: Incompatible return value type (got "Union[int, ndarray]", expected 741 # "int") --> 742 return nanops.nanargmin( # type: ignore[return-value] 743 delegate, skipna=skipna 744 ) File D:\Anaconda3\envs\tf_2.0\lib\site-packages\pandas\core\nanops.py:91, in disallow.__call__.<locals>._f(*args, **kwargs) 89 if any(self.check(obj) for obj in obj_iter): 90 f_name = f.__name__.replace("nan", "") ---> 91 raise TypeError( 92 f"reduction operation '{f_name}' not allowed for this dtype" 93 ) 94 try: 95 with np.errstate(invalid="ignore"): TypeError: reduction operation 'argmin' not allowed for this dtyp
最新发布
06-03
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值