17-lt-栈---实现各种栈

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.每日温度 (最小单调栈)

739.每日温度

思路:

首先进行的暴力求解,直接进行双重循环操作;但是时间复杂度比较大,

时间复杂度: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;
    }
}

总结:

空间和时间是互斥的,选择什么方式的优化 需要我们自己进行选择

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

带着希望活下去

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值