LeetCode 739. 每日温度(C、C++、python)

17 篇文章 0 订阅

根据每日 气温 列表,请重新生成一个列表,对应位置的输入是你需要再等待多久温度才会升高的天数。如果之后都不会升高,请输入 0 来代替。

例如,给定一个列表 temperatures = [73, 74, 75, 71, 69, 72, 76, 73],你的输出应该是 [1, 1, 4, 2, 1, 1, 0, 0]

提示:气温 列表长度的范围是 [1, 30000]。每个气温的值的都是 [30, 100] 范围内的整数。

C

/**
 * Return an array of size *returnSize.
 * Note: The returned array must be malloced, assume caller calls free().
 */
int* dailyTemperatures(int* temperatures, int temperaturesSize, int* returnSize) 
{
    int n=temperaturesSize;
    int* res=(int*)malloc(sizeof(int)*n);
    memset(res,0,sizeof(int)*n);
    int* tmp=(int*)malloc(sizeof(int)*n);
    int k=0;
    for(int i=0;i<n;i++)
    {
        while(k!=0 && temperatures[i]>temperatures[tmp[k-1]])
        {
            res[tmp[k-1]]=i-tmp[k-1];
            k--;
        }
        tmp[k++]=i;
    }
    *returnSize=n;
    return res;
}

C++

class Solution {
public:
    vector<int> dailyTemperatures(vector<int>& temperatures) 
    {
        int n=temperatures.size();
        vector<int> res(n,0);
        stack<int> tmp;
        for(int i=0;i<n;i++)
        {
            while(tmp.empty()!=1 && temperatures[i]>temperatures[tmp.top()])
            {
                res[tmp.top()]=i-tmp.top();
                tmp.pop();
            }
            tmp.push(i);
        }
        return res;
    }
};

python

class Solution:
    def dailyTemperatures(self, temperatures):
        """
        :type temperatures: List[int]
        :rtype: List[int]
        """
        n=len(temperatures)
        tmp=[]
        res=[0 for i in range(n)]
        for i in range(n):
            while len(tmp)!=0 and temperatures[i]>temperatures[tmp[-1]]:
                res[tmp[-1]]=i-tmp[-1]
                del tmp[-1]
            tmp.append(i)
        return res

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值