美文网首页Leetcode
Leetcode 739. Daily Temperatures

Leetcode 739. Daily Temperatures

作者: SnailTyan | 来源:发表于2018-09-20 19:10 被阅读8次

文章作者:Tyan
博客:noahsnail.com  |  CSDN  |  简书

1. Description

Daily Temperatures

2. Solution

  • Version 1
class Solution {
public:
    vector<int> dailyTemperatures(vector<int>& temperatures) {
        vector<int> result;
        for(int i = 0; i < temperatures.size(); i++) {
            bool flag = false;
            for(int j = i + 1; j < temperatures.size(); j++) {
                if(temperatures[j] > temperatures[i]) {
                    flag = true;
                    result.push_back(j - i);
                    break;
                }
            }
            if(!flag) {
                result.push_back(0);
            }
        }
        return result;
    }
};
  • Version 2
class Solution {
public:
    vector<int> dailyTemperatures(vector<int>& temperatures) {
        vector<int> result(temperatures.size(), 0);
        stack<int> s;
        for(int i = 0; i < temperatures.size(); i++) {
            while(!s.empty() && temperatures[s.top()] < temperatures[i]) {
                result[s.top()] = i - s.top();
                s.pop();
            }
            s.push(i);
        }
        return result;
    }
};

Reference

  1. https://leetcode.com/problems/daily-temperatures/description/

相关文章

网友评论

    本文标题:Leetcode 739. Daily Temperatures

    本文链接:https://www.haomeiwen.com/subject/wrwnnftx.html