1. 栈的实现
栈的实现可以使用队列进行
class MyStack {
private List<Integer> data; // store elements
public MyStack() {
data = new ArrayList<>();
}
/** Insert an element into the stack. */
public void push(int x) {
data.add(x);
}
/** Checks whether the queue is empty or not. */
public boolean isEmpty() {
return data.isEmpty();
}
/** Get the top item from the queue. */
public int top() {
return data.get(data.size() - 1);
}
/** Delete an element from the queue. Return true if the operation is successful. */
public boolean pop() {
if (isEmpty()) {
return false;
}
data.remove(data.size() - 1);
return true;
}
};
2.每日温度 (最小单调栈)
思路:
首先进行的暴力求解,直接进行双重循环操作;但是时间复杂度比较大,
时间复杂度:O(mn)空间复杂度:O(1)
想到了 总是重复的进行比较计算,因此参考优秀思路,使用单调栈可以将解决此问题。
遇到难题点:
结果:
//暴力解法
class Solution {
public int[] dailyTemperatures(int[] temperatures) {
for(int i = 0;i < temperatures.length;i++){
boolean flag = false;
for(int j = i; j < temperatures.length;j++){
if(temperatures[j] > temperatures[i]){
temperatures[i] = j-i;
flag = true;
break;
}
}
if(!flag){
temperatures[i] = 0;
}
}
return temperatures;
}
}
class Solution {
public int[] dailyTemperatures(int[] temperatures) {
Deque<Integer> stack = new LinkedList<>();
int[] ans = new int[temperatures.length];
for (int i = 0; i < temperatures.length; i++) {
while (!stack.isEmpty() && temperatures[i] > temperatures[stack.peek()]) {
Integer index = stack.pop();
ans[index] = i - index;
}
stack.push(i);
}
return ans;
}
}
总结:
空间和时间是互斥的,选择什么方式的优化 需要我们自己进行选择