9/3

 

우선 되는대로 풀어보기~~~

문제 설명이 완전 FILO 라서 stack을 써야겠다 싶었음.

#include <vector>
#include <stack>
#include <iostream>
using namespace std;

int solution(vector<int> order) {
    stack<int>st;
    st.push(0);
    int ans =0, n =0, i=1;
    while(st.top() <= order[n]){
        //cout << i << "**" << order[n] << "//"<< st.top() << "\n";
        if(i == order[n]){
            ans++; n++; i++;
        }
        else if(st.top() == order[n]){
            ans++; st.pop(); n++;
        }
        else {st.push(i); i++;}
    }
    return ans;
}

 

이러니까 오류가 나와서 확인해보니까

n이 끝까지 가면 ++되면서 범위가 벗어나는 오류가 발생함!

#include <vector>
#include <stack>
#include <iostream>
using namespace std;

int solution(vector<int> order) {
    stack<int>st;
    st.push(0);
    int ans =0, n =0, i=1;
    while(st.top() <= order[n] && n < order.size()){
        //cout << i << "**" << order[n] << "//"<< st.top() << "\n";
        if(i == order[n]){
            ans++; n++; i++;
        }
        else if(st.top() == order[n]){
            ans++; st.pop(); n++;
        }
        else {st.push(i); i++;}
    }
    return ans;
}

수정하니 성공~

+ Recent posts