155. Min Stack (E)

本文介绍了一种特殊的数据结构MinStack的设计与实现方法,该结构能在常数时间内完成压栈、弹栈、获取栈顶元素及获取当前栈中最小元素的操作。通过维护两个栈,即普通栈和最小值栈,实现了所有操作的高效执行。

Min Stack (E)

Design a stack that supports push, pop, top, and retrieving the minimum element in constant time.

  • push(x) – Push element x onto stack.
  • pop() – Removes the element on top of the stack.
  • top() – Get the top element.
  • getMin() – Retrieve the minimum element in the stack.

Example:

MinStack minStack = new MinStack();
minStack.push(-2);
minStack.push(0);
minStack.push(-3);
minStack.getMin();   --> Returns -3.
minStack.pop();
minStack.top();      --> Returns 0.
minStack.getMin();   --> Returns -2.

题意

设计一个栈结构,在实现栈的基础功能之外,还需要实现一个获取当前栈最小值的方法,每个操作的时间复杂度要求为O(1)O(1)O(1)

思路

维护两个栈来实现输出最小值:一个为普通栈stack,一个用于保存与当前普通栈中元素相对应的最小值栈minStack。push新元素x时,如果当前minStack为空,或者x值小于等于minStack栈顶元素,说明x是加入后普通栈中的最小值,需要在minStack入栈;pop栈顶元素x时,如果x与minStack栈顶元素相同,说明x正是当前普通栈中的最小值,也需要在minStack出栈。


代码实现

class MinStack {
    private LinkedList<Integer> stack;
    private LinkedList<Integer> minStack;

    /** initialize your data structure here. */
    public MinStack() {
        stack = new LinkedList<>();
        minStack = new LinkedList<>();
    }
    
    public void push(int x) {
        // 注意要使用<=,不然会引发NullPointerException
        if (minStack.isEmpty() || x <= minStack.peek()) {
            minStack.push(x);    
        }
        stack.push(x);
    }
    
    public void pop() {
        int min = minStack.peek();
        if (stack.peek() == min) {
            minStack.pop();
        }
        stack.pop();
    }
    
    public int top() {
        return stack.peek();
    }
    
    public int getMin() {
        return minStack.peek();
    }
}

/**
 * Your MinStack object will be instantiated and called as such:
 * MinStack obj = new MinStack();
 * obj.push(x);
 * obj.pop();
 * int param_3 = obj.top();
 * int param_4 = obj.getMin();
 */
--------------------------------------------------------------------------- ValueError Traceback (most recent call last) /tmp/ipykernel_553597/306262114.py in <module> 7 ## Training 8 # Epoch_list,Loss_list = model_train(batchsize,channel_SNR_db1,noise_init,nl_factor,eq_flag,norm_epsilon,earlystop_epoch) ----> 9 Epoch_list,Loss_list, Min_Distance_list = model_train(batchsize,channel_SNR_db1,noise_init,nl_factor,eq_flag,norm_epsilon,earlystop_epoch, min_distance_threshold=0.7,flags_schedule=[(1, 0), (0, 1), (1, 1)],iter_per_stage=50) /tmp/ipykernel_553597/4102420687.py in model_train(batchsize, channel_SNR, noise_init, nl_factor, eq_flag, epsilon, earlystop_epoch, min_distance_threshold, flags_schedule, iter_per_stage) 58 59 (batch_loss, batch_loss_Eq, NGMI, GMI, entropy_S, ---> 60 p_s, norm_constellation, x, min_distance) = train_step( 61 channel_SNR, noise_tf, GS_flag_now, PS_flag_now, eq_flag, epsilon, min_distance_threshold 62 ) ~/miniconda3/lib/python3.8/site-packages/tensorflow/python/util/traceback_utils.py in error_handler(*args, **kwargs) 151 except Exception as e: 152 filtered_tb = _process_traceback_frames(e.__traceback__) --> 153 raise e.with_traceback(filtered_tb) from None 154 finally: 155 del filtered_tb /tmp/__autograph_generated_file_jsnzuik.py in tf__train_step(inp_SNR, noise, GS_flag, PS_flag, eq_flag, epsilon, min_distance_threshold) 39 batch_size = ag__.converted_call(ag__.ld(tf).shape, (ag__.ld(p_s),), None, fscope)[0] 40 batch_indices = ag__.converted_call(ag__.ld(tf).tile, (ag__.converted_call(ag__.ld(tf).range, (ag__.ld(batch_size),), None, fscope)[:, ag__.ld(tf).newaxis, ag__.ld(tf).newaxis], [1, ag__.ld(M_int), ag__.ld(k)]), None, fscope) ---> 41 gather_indices = ag__.converted_call(ag__.ld(tf).stack, ([ag__.ld(batch_indices), ag__.converted_call(ag__.ld(tf).tile, (ag__.ld(topk_indices)[:, :, ag__.ld(tf).newaxis, :], [1, 1, ag__.ld(k), 1]), None, fscope)],), dict(axis=(- 1)), fscope) 42 neighbor_probs = ag__.converted_call(ag__.ld(tf).gather_nd, (ag__.ld(p_s), ag__.ld(gather_indices)), None, fscope) 43 neighbor_sum = ag__.converted_call(ag__.ld(tf).reduce_sum, (ag__.ld(neighbor_probs),), dict(axis=(- 1)), fscope) ValueError: in user code: File "/tmp/ipykernel_553597/675414708.py", line 77, in train_step * gather_indices = tf.stack([ ValueError: Shapes must be equal rank, but are 3 and 4 From merging shape 0 with other shapes. for '{{node stack_1}} = Pack[N=2, T=DT_INT32, axis=-1](Tile, Tile_1)' with input shapes: [1,8,3], [1,8,3,3].
08-22
``` import numpy as np from stl import mesh import matplotlib.pyplot as plt from mpl_toolkits.mplot3d import Axes3D from scipy.interpolate import splprep, splev from collections import defaultdict def extract_boundary_edges(stl_file): # 原提取边界边函数保持不变 stl_mesh = mesh.Mesh.from_file(stl_file) triangles = stl_mesh.vectors edge_count = {} for triangle in triangles: for i in range(3): edge = tuple(sorted([tuple(triangle[i]), tuple(triangle[(i + 1) % 3])])) edge_count[edge] = edge_count.get(edge, 0) + 1 return [edge for edge, count in edge_count.items() if count == 1] def connect_contours(boundary_edges, tolerance=1e-6): # 构建邻接表 adjacency = defaultdict(list) for edge in boundary_edges: p1, p2 = edge adjacency[p1].append(p2) adjacency[p2].append(p1) # 拓扑排序连接轮廓 contours = [] visited = set() for start_point in adjacency: if start_point in visited: continue current = start_point contour = [np.array(current)] visited.add(current) while True: neighbors = [n for n in adjacency[current] if tuple(n) not in visited] if not neighbors: break next_point = neighbors[0] contour.append(np.array(next_point)) visited.add(tuple(next_point)) current = tuple(next_point) # 闭合检测 if np.linalg.norm(contour[0] - contour[-1]) < tolerance: contour.append(contour[0]) contours.append(np.array(contour)) return contours def fit_contours(contours, smooth=0.05, num_points=100): fitted_curves = [] for contour in contours: # 转换为参数化样条 tck, u = splprep(contour.T, s=smooth) u_new = np.linspace(u.min(), u.max(), num_points) x_new, y_new, z_new = splev(u_new, tck) fitted_curves.append(np.column_stack((x_new, y_new, z_new))) return fitted_curves def visualize_results(contours, fitted_curves): fig = plt.figure(figsize=(12, 6)) # 原始边界可视化 ax1 = fig.add_subplot(121, projection='3d') for contour in contours: ax1.plot(contour[:, 0], contour[:, 1], contour[:, 2], 'b-', alpha=0.5) ax1.set_title('原始边界边') # 拟合结果可视化 ax2 = fig.add_subplot(122, projection='3d') for curve in fitted_curves: ax2.plot(curve[:, 0], curve[:, 1], curve[:, 2], 'r-', lw=2) ax2.set_title('拟合曲线') for ax in [ax1, ax2]: ax.set_box_aspect([1, 1, 0.1]) ax.set_xlabel('X') ax.set_ylabel('Y') ax.set_zlabel('Z') plt.tight_layout() plt.show() # 主程序流程 stl_file = 'source.stl' # 步骤1:提取边界边 boundary_edges = extract_boundary_edges(stl_file) print(f"提取边界边数量: {len(boundary_edges)}") # 步骤2:连接成连续轮廓 contours = connect_contours(boundary_edges) print(f"发现轮廓数量: {len(contours)}") # 步骤3:进行样条拟合 fitted_curves = fit_contours(contours) # 步骤4:可视化对比 visualize_results(contours, fitted_curves)```Traceback (most recent call last): File "D:\Test\project\提取边界边3.py", line 111, in <module> fitted_curves = fit_contours(contours) File "D:\Test\project\提取边界边3.py", line 65, in fit_contours tck, u = splprep(contour.T, s=smooth) File "C:\Users\18018\.conda\envs\test\lib\site-packages\scipy\interpolate\_fitpack_py.py", line 155, in splprep res = _impl.splprep(x, w, u, ub, ue, k, task, s, t, full_output, nest, per, File "C:\Users\18018\.conda\envs\test\lib\site-packages\scipy\interpolate\_fitpack_impl.py", line 159, in splprep raise TypeError('m > k must hold') TypeError: m > k must hold
03-20
基于部落竞争与成员合作算法(CTCM)融合动态窗口法DWA的无人机三维动态避障方法研究,MATLAB代码 动态避障路径规划:基于部落竞争与成员合作算法(CTCM)融合动态窗口法DWA的无人机三维动态避障方法研究,MATLAB 融合DWA的青蒿素优化算法(AOA)求解无人机三维动态避障路径规划,MATLAB代码 基于动态环境下多智能体自主避障路径优化的DWA算法研究,MATLAB代码 融合DWA的青蒿素优化算法AOA求解无人机三维动态避障路径规划,MATLAB代码 基于DWA的多智能体动态避障路径规划算法研究,MATLAB代码 融合动态窗口法DWA的粒子群算法PSO求解无人机三维动态避障路径规划研究,MATLAB代码 基于粒子群算法PSO融合动态窗口法DWA的无人机三维动态避障路径规划研究,MATLAB代码 基于ACOSRAR-DWA无人机三维动态避障路径规划,MATLAB代码 基于ACOSRAR-DWA无人机三维动态避障路径规划,MATLAB代码 基于DWA的动态环境下无人机自主避障路径优化,MATLAB代码 基于DWA的动态环境下机器人自主避障路径规划,MATLAB代码 基于城市场景下RRT、ACO、A*算法的无人机三维路径规划方法研究,MATLAB代码 基于城市场景下无人机三维路径规划的导航变量的多目标粒子群优化算法(NMOPSO),MATLAB代码 导航变量的多目标粒子群优化算法(NMOPSO)求解复杂城市场景下无人机三维路径规划,MATLAB代码 原创:5种最新多目标优化算法求解多无人机协同路径规划(多起点多终点,起始点、无人机数、障碍物可自定义),MATLAB代码 原创:4种最新多目标优化算法求解多无人机协同路径规划(多起点多终点,起始点、无人机数、障碍物可自定义),MATLAB代码 高维超多目标优化:基于导航变量的多目标粒子群优化算法(NMOPSO)的无人机三维
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值