LeetCode·每日一题·1475.商品折扣后的最终价格·单调栈

链接:https://leetcode.cn/problems/final-prices-with-a-special-discount-in-a-shop/solution/-by-xun-ge-v-x51o/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。 

题目

 

示例

 

思路

解题思路
【暴力求解】

题意其实就是让我们在数组中寻找当前位置之后的第一个小于当前位置的元素

不能想到使用双指针,暴力枚举,一个指针指向当前位置,另外一个指针去寻找第一个并当前位置小的元素

【单调栈】

在上述暴力法中,我们遍历了两次数组,时间消耗比较大,但是好在数组长度 <=500 比较小,还不至于超时,但是如果数组长度再长一点,暴力求解就不行了,需要使用单调栈优化
其实单调栈也是暴力枚举,只是优化了寻找第一个小于当前元素的过程

具体实现看代码,注释超级详细

代码

【暴力求解】

/**
 * Note: The returned array must be malloced, assume caller calls free().
 */
int* finalPrices(int* prices, int pricesSize, int* returnSize){
    *returnSize = pricesSize;
    for(int i = 0, j; i < pricesSize; i++)//枚举每一个元素
    {
        bool logo = false;//记录是否存在小于值
        for(j = i+1; j < pricesSize; j++)//寻找第一个小于值
        {
            if(prices[i] >= prices[j])
            {
                logo = true;
                break;
            }
        }
        if(logo) prices[i] -= prices[j];//如果存在小于就计算
    }
    return prices;
}

作者:xun-ge-v
链接:https://leetcode.cn/problems/final-prices-with-a-special-discount-in-a-shop/solution/-by-xun-ge-v-x51o/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。

【单调栈】

/**
 * Note: The returned array must be malloced, assume caller calls free().
 */
int* finalPrices(int* prices, int pricesSize, int* returnSize) {
    int *ans = (int *)malloc(sizeof(int) * pricesSize);
    int stack[pricesSize];//初始化变量
    int top = 0;
    for (int i = pricesSize - 1; i >= 0; i--) {//枚举每一个元素
        while (top > 0 && stack[top - 1] > prices[i]) {//弹出比当前元素大的值
            top--;
        }
        ans[i] = top == 0 ? prices[i] : prices[i] - stack[top - 1];//如果栈中有元素,栈顶即第一个小于值
        stack[top++] = prices[i];
    }
    *returnSize = pricesSize;
    return ans;
}

作者:xun-ge-v
链接:https://leetcode.cn/problems/final-prices-with-a-special-discount-in-a-shop/solution/-by-xun-ge-v-x51o/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值