[프로그래머스/C++] 뒤에 있는 큰 수 찾기

Hanbi·2023년 3월 30일
0

Problem Solving

목록 보기
60/108
post-thumbnail

문제

https://school.programmers.co.kr/learn/courses/30/lessons/154539

풀이

처음에 이중 for문으로 단순 index 비교해서 풀었는데 시간초과 남
stack 이용

코드

#include <vector>
#include <stack>

using namespace std;

vector<int> solution(vector<int> numbers) {
    int n = numbers.size();
    vector<int> answer(n, -1);
    stack<int> s;
    
    for(int i=0; i<n; i++) {
        while(!s.empty() && numbers[s.top()] < numbers[i]) {
            answer[s.top()] = numbers[i];
            s.pop();
        }
        
        s.push(i); //뒷 큰수를 찾지 못한 수의 "인덱스"가 stack에 쌓이는 것
    }
    
    return answer;
}
profile
👩🏻‍💻

0개의 댓글