定义栈的数据结构,要求添加一个 min 函数,能够得到栈的最小元素

题目:

设计包含 min 函数的栈。
定义栈的数据结构,要求添加一个
min函数,能够得到栈的最小元素。要求函数 minpush以及 pop的时间复杂度都是 O(1)。 

解题思路:

栈是后进先出的数据结构,要求查询得到栈的最小元素,我们内部实现可以设计两个栈A、B,A栈保存用户进栈数据,B栈保存当前A栈中最小元素。但用户数据进栈,判断B栈的top元素,如果小于用户数据,则B栈top元素再次进入B栈,否则用户数据进入B栈。A栈与B栈一一对应,B栈index索引标志A栈index索引时的最小数据。

由此思路,我们封装一个MinEntry,用于保存当前用户数据,和当前栈的最小值。

代码实现:

public class MinStack {
	private List<MinEntry> stack = null;
	
	public MinStack(){
		stack = new ArrayList<MinEntry>();
	}
	
	public MinStack(int size){
		stack = new ArrayList<MinEntry>();
	}
	
	public void push(Integer value){
		Integer minest = value;
		if (stack.size() > 0){
			MinEntry top = stack.get(stack.size() - 1);
			if (top.minest < minest){
				minest = top.minest;
			}
		}
		stack.add(new MinEntry(value, minest));
	}
	
	public MinEntry pop(){
		int n = stack.size();
		if (n <= 0){
			throw new EmptyStackException();
		}
		return stack.remove(n - 1);
	}
	
	public MinEntry peek(){
		int n = stack.size();
		if (n <= 0){
			throw new EmptyStackException();
		}
		return stack.get(n - 1);
	}
	
	public boolean empty(){
		return stack.isEmpty();
	}
	
	
	class MinEntry{
		private Integer value;
		private Integer minest;
		public MinEntry(Integer value, Integer minest){
			this.value = value;
			this.minest = minest;
		}
		public Integer getValue(){
			return this.value;
		}
		public Integer getMinest(){
			return minest;
		}
	}
}
Junit代码如下:

public class MinStackTest {

	@Test
	public void testPop() {
		int count = 100000;
		Random random = new Random();
		List<Integer> minList = new ArrayList<Integer>(count);
		MinStack stack = new MinStack(count);
		Integer minest = null;
		for (int i = 0; i < count; i++){
			Integer value = random.nextInt();
			if (minest == null || value < minest){
				minest = value;
			}
			minList.add(minest);
			stack.push(value);
		}
		Collections.sort(minList);
		for (int i = 0; i < count; i++){
			assertEquals(stack.pop().getMinest(), minList.get(i));
		}
	}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值