https://school.programmers.co.kr/learn/courses/30/lessons/131704?language=java
import java.util.*;
class Solution {
public int solution(int[] order) {
int answer = 0;
int n = order.length;
Stack<Integer> st = new Stack<>();
int realSize = 1;
int boxIndex = 0;
while(realSize <= n){
if(realSize == order[boxIndex]){
realSize++;
boxIndex++;
answer++;
}else if(!st.empty() && order[boxIndex] == st.peek()){
boxIndex++;
answer++;
st.pop();
}else{
st.push(realSize++);
}
}
while (!st.isEmpty() && st.peek() == order[boxIndex]) {
st.pop();
answer++;
boxIndex++;
}
return answer;
}
}
문제 이해하는데 오래 걸렸다.
실제 존재하는 박스의 인덱스와 '택배 기사님' 이 원하는 인덱스가 따로 있다라는것을 이해해야한다.
즉 원하는 순서와 상관없이 존재하는 순서의 인덱스(1번부터 시작)가 있는것.
그것이 realSize(1번부터 시작) 와 boxIndex 이다.
풀이 자체는 간단하다.
만약 realSize 가 기사님이 원하는 박스의 순서와 동일하다면 realSize 와 boxIndex 를 증가시키고...
동일하지 않지만 스택에 보관해둔 녀석이 order[boxIndex] 와 동일하다면 스택 하나 지워주고 boxIndex 증가 시킨다.
realSize 는 안올려준다. 왜? 이미 스택에 넣을떄 올려줬으니까...
그리고 해당하지 않으면 스택에 넣어주고.
그러다가 다 돌았는데도 스택 안비었을수도 잇으니까 스택 돌면서 조건 확인 후 답 올려준다.

적당한 속도