문제: https://leetcode.com/problems/daily-temperatures/
Daily Temperatures - LeetCode
Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview.
leetcode.com
현재 날짜의 기온보다 높은 기온이 나오는 날짜의 차를 각각 구하는 문제다.
class Solution {
public:
vector<int> dailyTemperatures(vector<int>& temperatures) {
int n = temperatures.size();
vector<int> ans(n, 0);
stack<int> stk;
for(int i = n - 1; i >= 0; i—){
int v = temperatures[i];
while(!stk.empty() && temperatures[stk.top()] <= v){
stk.pop();
}
if(!stk.empty()){
int pos = stk.top();
ans[i] = pos - i;
}
stk.push(i);
}
return ans;
}
};
첫 번째 솔루션은 stack에다가 현재 값보다 높은 값들만 저장한다. 이러면 처음 높은 값이 stack의 top에 있으며, 없으면 pop을 하면 되므로 답을 구할 수 있다.
Time complexity: O(N)
Space complexity: O(N)
class Solution {
public:
vector<int> dailyTemperatures(vector<int>& temperatures) {
int n = temperatures.size();
vector<int> ans(n, 0);
int hottest = 0;
for(int i = n - 1; i >= 0; i—){
int v = temperatures[i];
if(v >= hottest){
hottest = v;
continue;
}
int days = 1;
while(temperatures[i + days] <= v){
days += ans[i + days];
}
ans[i] = days;
}
return ans;
}
};
ans vector에 현 ith 포지션에서 그 보다 높은 온도가 나오는 위치의 차를 가지고있다. 즉, 현재 포지션에서 그 차이만큼 뛰면 해당 온도보다 높은 온도를 extra memory 없이 구할 수 있다.
Time complexity: O(N)
Space complexity: O(1)
'* Computer Science > Algorithm' 카테고리의 다른 글
1286. Iterator for Combination (0) | 2021.11.14 |
---|---|
1178. Number of Valid Words for Each Puzzle (0) | 2021.11.10 |
1368. Minimum Cost to Make at Least One Valid Path in a Grid (0) | 2021.11.04 |
1202. Smallest String With Swaps (0) | 2021.11.03 |
1711. Count Good Meals (0) | 2021.10.28 |