Sorry, your browser cannot access this site
This page requires browser support (enable) JavaScript
Learn more >

最小栈

题目

lettcode-155题
难度:简单1633055736251

解题思路

题目基本上就是要求找出一个栈中最小的值,通过java中内置的栈的方法即可实现这一目标

首先我的想法是通过遍历比较所有的值来找出最小的那个值,但是这样子消耗了较多的时间,而且题目希望是设计一种栈的结构,而不是直接用栈的方法。

所以后面换了一种新的方法,就是使用链表来实现,这样子的效率是较高的,相比于之前的方法,用时整整少了200多毫秒This is a picture without description

具体实现方式如下

具体代码(第一种思路)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
class MinStack {

Stack<Integer> stack;
public MinStack() {
stack = new Stack<Integer>();
}

public void push(int val) {
stack.push(val);
}

public void pop() {
stack.pop();
}

public int top() {
return stack.peek();
}

public int getMin() {
int min=stack.get(0);;
for (int i=0;i<stack.size();i++){
if (stack.get(i)<min){
min=stack.get(i);
}
}
return min;
}
}

具体代码(第二种思路)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
class MinStack {

private Node head;

public void push(int x) {
if(head == null)
head = new Node(x, x);
else
head = new Node(x, Math.min(x, head.min), head);
}

public void pop() {
head = head.next;
}

public int top() {
return head.val;
}

public int getMin() {
return head.min;
}

private class Node {
int val;
int min;
Node next;

private Node(int val, int min) {
this(val, min, null);
}

private Node(int val, int min, Node next) {
this.val = val;
this.min = min;
this.next = next;
}
}
}