我的代码:
public class MinStack {
// 栈一般是用 数组,但是数组一般要在构造的时候就声明大小;
// 或者使用 node 链表,不过得定义一个 链表结构
// 所以这道题我选择最简单的,使用容器,比如List
private int currentMin;
private ArrayList<Integer> nums; // 注意这里有一个经常性的错误
/** initialize your data structure here. */
public MinStack() {
nums = new ArrayList<Integer>();
}
public void push(int x) {
// 如果当前list为空的话,最小为当前
if(nums.size() == 0){
currentMin = x;
} else {
currentMin = (x<currentMin)?x:currentMin;
}
nums.add(x);
}
public void pop() {
int size = nums.size();
if(nums.get(size-1) == currentMin){
// 遍历以获取新的最小值
nums.remove(size-1);
// 如果此时没有元素了,则不用遍历
if(nums.size() != 0)
currentMin = getMinNum(nums);
} else {
nums.remove(size-1);
}
}
public int top() {
int size = nums.size();
return nums.get(size-1);
}
public int getMin() {
return currentMin;
}
private int getMinNum(ArrayList<Integer> nums){
int size = nums.size();
int tempMin = nums.get(0);
// 这里注意,不能在for循环里调用函数
for(int i=1;i<size;i++){
int temp = nums.get(i);
if(tempMin > temp){
tempMin = temp;
}
}
return tempMin;
}
}
一些知识点:
java中模拟一个Stack的方法
- 使用数组,但是数组是要在一开始构造的时候就声明大小的
- 使用链表,但是得构建一个node类
- 使用容器
因为使用容器是最方便的,所以我选择用ArrayList来实现,同样的也可以使用 Stack,LinkedList来实现
关于ArrayList 和 LinkedList的遍历方法和性能
我这里只写一些关键的部分:
遍历方法大概可以分为两种:foreach,迭代器和for循环;
(在数据大小为100000之外)
对于ArrayList,最快的是 for循环,最慢的是 foreach
对于LinkedList,最快的是 foreach,最慢的是 for循环
数组可以使用get(i)方法是极快的,因为可以下标直接取,时间复杂度为 O(1),但是链表的话,get(i)的时间复杂度为 O(n)
因为在本题中所有的删除都是删除end元素,所以可以选择 arrayList
其他
一个经常遇到的错误
Arraylist<int>
这种写法是错误的,因为ArrayList中只能是对象,而不能是基本类型,所以应该用 Integer
如何设置最小数
在写程序的时候,往往需要设置到 极限最大值或者极限最小值,在java中可以使用 Integer 类的常量表示:Integer.MAX_VALUE
另外 int 的范围 -2147483648 - 2147483647
for循环中不用调用.size()方法
切勿将for(int i=0;i<nums.size();i++)
这样写每次循环都会调用一遍 .size() 方法,大大增大了时间