zoukankan      html  css  js  c++  java
  • LeetCode 739. 每日温度

    题目描述:

    解法一(暴力):

    class Solution {
    public:
        vector<int> dailyTemperatures(vector<int>& T) {
            int n = T.size();
            vector<int> res(n, 0);
            for (int i = 0; i < n; i++) {
                for (int j = i + 1; j < n; j++) {
                    if (T[j] > T[i]) {
                        res[i] = j - i;
                        break;
                    }
                }
            }
            return res;
        }
    };

    解法二(跳跃):

    class Solution {
    public:
        vector<int> dailyTemperatures(vector<int>& T) {
            int n = T.size();
            vector<int> res(n, 0);
            for (int i = n - 2; i >= 0; i--) {
                for (int j = i + 1; j<n; j += res[j]) {
                    if (T[i] < T[j]) {
                        res[i] = j - i;
                        break;
                    }
                    else if (res[j] == 0) {
                        res[i] = 0;
                        break;
                    }
                }
            }
            return res;
        }
    };

    解法三(单调栈):

    class Solution {
    public:
        vector<int> dailyTemperatures(vector<int>& T) {
            stack<int> stk;
            vector<int> res;
            for (int i = T.size() - 1; i >= 0; i--) {
                while (!stk.empty() && T[i] >= T[stk.top()]) {
                    stk.pop();
                }
                if (stk.empty()) res.push_back(0);
                else res.push_back(stk.top() - i);
                stk.push(i);
            }
            reverse(res.begin(), res.end());
            return res;
        }
    };
  • 相关阅读:
    基于Twisted的简单聊天室
    小学题的python实现
    初识Go(8)
    初识Go(7)
    初识Go(6)
    初识Go(5)
    初识Go(4)
    初识Go(3)
    初识Go(2)
    初识Go(1)
  • 原文地址:https://www.cnblogs.com/oneDongHua/p/14263999.html
Copyright © 2011-2022 走看看