返回

单调栈解法巧妙破解Leetcode145商品折扣难题【Java&C++】

后端

单调栈的奥秘

单调栈是一种特殊的数据结构,它有着一个有趣的特点:栈中元素总是按照某种顺序排列,比如从小到大或从大到小。单调栈的强大之处在于,它可以帮助我们快速找到某一特定元素在栈中的位置,从而简化算法的设计和实现。

单调栈在Leetcode145题中的妙用

在Leetcode145题中,我们使用单调栈来维护当前未被折扣的商品价格。当我们遍历商品列表时,我们会将当前商品的价格与栈顶元素进行比较。如果当前商品的价格小于或等于栈顶元素,那么我们将当前商品的价格入栈。否则,我们将栈顶元素出栈,并将其价格与当前商品的价格相乘,得到当前商品的折扣价。

Java解决方案

import java.util.Stack;

class Solution {
    public int[] finalPrices(int[] prices) {
        Stack<Integer> stack = new Stack<>();
        int[] finalPrices = new int[prices.length];

        for (int i = 0; i < prices.length; i++) {
            while (!stack.isEmpty() && prices[stack.peek()] >= prices[i]) {
                finalPrices[stack.peek()] = prices[i];
                stack.pop();
            }
            stack.push(i);
        }

        while (!stack.isEmpty()) {
            finalPrices[stack.peek()] = 0;
            stack.pop();
        }

        return finalPrices;
    }
}

C++解决方案

#include <stack>
#include <vector>

using namespace std;

class Solution {
public:
    vector<int> finalPrices(vector<int>& prices) {
        stack<int> stack;
        vector<int> finalPrices(prices.size());

        for (int i = 0; i < prices.size(); i++) {
            while (!stack.empty() && prices[stack.top()] >= prices[i]) {
                finalPrices[stack.top()] = prices[i];
                stack.pop();
            }
            stack.push(i);
        }

        while (!stack.empty()) {
            finalPrices[stack.top()] = 0;
            stack.pop();
        }

        return finalPrices;
    }
};

总结

单调栈算法是一种非常有用的数据结构,它可以帮助我们解决许多复杂的问题。在Leetcode145题中,我们使用单调栈来维护当前未被折扣的商品价格,并通过比较栈顶元素和当前商品的价格来计算折扣价。这种方法简单高效,非常适合解决Leetcode145题。