1. 문제 풀이 아이디어
- 스택을 사용하여 문제를 해결할 수 있다.
2. 나의 정답 코드
class Solution {
public int solution(int[] ingredient) {
Stack<Integer> stack = new Stack<>();
int answer = 0;
for (int i : ingredient) {
if (i == 1 && stack.size() > 2 && stack.get(stack.size() - 1) == 3 && stack.get(stack.size() - 2) == 2 && stack.get(stack.size() - 3) == 1) {
stack.pop();
stack.pop();
stack.pop();
answer++;
} else {
stack.push(i);
}
}
return answer;
}
}
3. 정리
ingredient
배열을 순회하며, 요소가 1이고 스택의 크기가 3 이상이며, 마지막 세 요소가 1, 2, 3의 순서로 되어 있으면 이 값을 제거하고 결과값을 증가시킨다.
- 조건을 만족하지 않을 경우 현재 값을 스택에 추가한다.
- 반복문이 끝난 후 결과값을 반환하여 문제를 해결한다.
4. 더 좋은 코드 리뷰
class Solution {
public int solution(int[] ingredient) {
int[] stack = new int[ingredient.length];
int sp = 0;
int answer = 0;
for (int i : ingredient) {
stack[sp++] = i;
if (sp >= 4 && stack[sp - 1] == 1
&& stack[sp - 2] == 3
&& stack[sp - 3] == 2
&& stack[sp - 4] == 1) {
sp -= 4;
answer++;
}
}
return answer;
}
}
- 택 대신 배열을 사용함으로써 더 효율적이고 빠르게 처리할 수 있다.
Share article