1. 程式人生 > >LeetCode 739. 每日溫度(C、C++、python)

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

根據每日 氣溫 列表,請重新生成一個列表,對應位置的輸入是你需要再等待多久溫度才會升高的天數。如果之後都不會升高,請輸入 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