이 코드는 스택으로
public int solution(int[][] board, int[] moves) {
int answer = 0;
Stack<Integer> stack = new Stack<>();
for (int y: moves) {
y = y - 1;
for (int x = 0; x < board[y].length; x++) {
if (board[x][y] == 0) continue;
if (!stack.isEmpty() && stack.peek() == board[x][y]) {
answer++;
stack.pop();
} else {
stack.push(board[x][y]);
}
board[x][y] = 0;
break;
}
}
return answer * 2;
}
이 코드는 LinkedList로
public int solution(int[][] board, int[] moves) {
int answer = 0;
LinkedList<Integer> stack = new LinkedList<>();
for (int y: moves) {
y = y - 1;
for (int x = 0; x < board[y].length; x++) {
if (board[x][y] == 0) continue;
if (!stack.isEmpty() && stack.getLast() == board[x][y]) {
answer++;
stack.removeLast();
} else {
stack.addLast(board[x][y]);
}
board[x][y] = 0;
break;
}
}
return answer * 2;
}
예전에 강사님께서 스택보다 큐가 속도가 빠르다고 알려주셨던게 갑자기 생각나서
작성해봤다!
🔻아래는 LinkedList로 풀었을때
🔻아래는 Stack으로 풀었을때
이 문제는 효율성 테스트가 없는 문제라서;;
이 문제에서는 LinkedList가 조금 더 빠른 성능을 보였다.
감사하게도 이런 내용을 쉽게 배운 것 같다 🙇
테스트 케이스는 어떤 데이터가 들어있는지 모르겠지만,
아주 많은 데이터를 다루는 케이스가 테스트 케이스로 들어온다면 LinkedList가 훨씬 빠름이 드러날것 같다는 생각을 했다 🤔