s0739
All checks were successful
continuous-integration/drone/push Build is passing

This commit is contained in:
Sainnhe Park 2022-12-16 15:08:10 +08:00
parent f46902b970
commit ac57b13edb
4 changed files with 77 additions and 0 deletions

View File

@ -0,0 +1,14 @@
#ifndef S0739_DAILY_TEMPERATURES_HPP
#define S0739_DAILY_TEMPERATURES_HPP
#include <vector>
#include <stack>
using namespace std;
class S0739 {
public:
vector<int> dailyTemperatures(vector<int>& temperatures);
};
#endif

View File

@ -13,6 +13,18 @@
[1047. 删除字符串中的所有相邻重复项](https://leetcode.cn/problems/remove-all-adjacent-duplicates-in-string/) [1047. 删除字符串中的所有相邻重复项](https://leetcode.cn/problems/remove-all-adjacent-duplicates-in-string/)
### 变体:单调栈
栈中的元素单调递增或单调递减。
使用场景:通常是一维数组,要寻找任一个元素的右边或者左边第一个比自己大或者小的元素的位置。
时间复杂度O(n)
经典题目:
[739. 每日温度](https://leetcode.com/problems/daily-temperatures/)
## 队列 ## 队列
使用场景: 使用场景:

View File

@ -0,0 +1,27 @@
#include "s0739_daily_temperatures.hpp"
vector<int> S0739::dailyTemperatures(vector<int>& temperatures) {
int len = temperatures.size();
if (len == 0) {
return vector<int> {};
} else if (len == 1) {
return vector<int> {0};
}
// 栈中的元素为向量的下标
// 向量下标对应的元素从栈底到栈顶单调递增
stack<int> s;
s.push(0);
// 初始化 ans 中的所有元素为 0
vector<int> ans(len, 0);
for (int i{1}; i < len; ++i) {
while (temperatures[i] > temperatures[s.top()]) {
ans[s.top()] = i - s.top();
s.pop();
if (s.empty()) {
break;
}
}
s.push(i);
}
return ans;
}

View File

@ -0,0 +1,24 @@
#include "s0739_daily_temperatures.hpp"
#include <gtest/gtest.h>
TEST(Problem739, Case1) {
vector<int> temperatures{73, 74, 75, 71, 69, 72, 76, 73};
vector<int> expected{1, 1, 4, 2, 1, 1, 0, 0};
S0739 solution;
EXPECT_EQ(solution.dailyTemperatures(temperatures), expected);
}
TEST(Problem739, Case2) {
vector<int> temperatures{30, 40, 50, 60};
vector<int> expected{1, 1, 1, 0};
S0739 solution;
EXPECT_EQ(solution.dailyTemperatures(temperatures), expected);
}
TEST(Problem739, Case3) {
vector<int> temperatures{30, 60, 90};
vector<int> expected{1, 1, 0};
S0739 solution;
EXPECT_EQ(solution.dailyTemperatures(temperatures), expected);
}