Algorithm/프로그래머스
[프로그래머스]스택/큐 : 탑 (level 2) (c++)
HBGB
2020. 4. 29. 18:36
https://programmers.co.kr/learn/courses/30/lessons/42588
프로그래머스
코드 중심의 개발자 채용. 스택 기반의 포지션 매칭. 프로그래머스의 개발자 맞춤형 프로필을 등록하고, 나와 기술 궁합이 잘 맞는 기업들을 매칭 받으세요.
programmers.co.kr
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
|
#include <string>
#include <vector>
#include <stack>
using namespace std;
vector<int> solution(vector<int> heights) {
// 스택: 자기보다 더 작은 탑을 아직 찾지 못한 탑 idx
stack<int> s;
vector<int> answer(heights.size(), 0);
for (int i = 0; i < heights.size(); i++)
{
// 스택 top 높이 <= i 높이 --> 스택 pop
while (!s.empty() && heights[s.top()] <= heights[i])
{
s.pop();
}
// 스택 top 높이 > i 높이 --> 답 벡터 입력
if (!s.empty() && heights[s.top()] > heights[i])
{
answer[i] = s.top() + 1;
}
s.push(i);
}
return answer;
}
Colored by Color Scripter
|
스택 기준만 잘 잡으면 깔끔하게 풀린다