프로그래머스/2레벨

[프로그래머스/C++] 택배상자

Koalitsiya 2024. 1. 10. 16:16
 

프로그래머스

코드 중심의 개발자 채용. 스택 기반의 포지션 매칭. 프로그래머스의 개발자 맞춤형 프로필을 등록하고, 나와 기술 궁합이 잘 맞는 기업들을 매칭 받으세요.

programmers.co.kr

 

처음 접근할 때 이상하게 접근해서 시간이 걸린 문제였다.

 

 

1. 보조 컨테이너 벨트 역할을 할 스택을 생성

2. 컨테이너 벨트에 있는 i번째 상자를 보조 컨테이너 벨트에 넣음

3. 이후 subConveyer의 크기가 0이 아니고 subConveyer의 top과 order[answer]가 같을 때 answer를 증가시키고 subConveyer에 pop을 수행

4. 위를 order의 크기만큼 반복

#include <string>
#include <vector>
#include <stack>

using namespace std;

int solution(vector<int> order) {
    int answer = 0;
    
    stack<int> subConveyer;
    
    for(int i = 1; i <= order.size(); i++) {
        subConveyer.push(i);
        
        while (subConveyer.size() != 0 && subConveyer.top() == order[answer]){
            answer++;
            subConveyer.pop();
        }
    }
    
    return answer;
}