반응형
https://school.programmers.co.kr/learn/courses/30/lessons/64061
프로그래머스
코드 중심의 개발자 채용. 스택 기반의 포지션 매칭. 프로그래머스의 개발자 맞춤형 프로필을 등록하고, 나와 기술 궁합이 잘 맞는 기업들을 매칭 받으세요.
programmers.co.kr
2차원 배열이 존재하고, 각 라인별로 0이 아닌 숫자를 가져와 스택에 저장하며 푸는 문제입니다.
주의할 점은 스택에 숫자를 저장하면 기존 2차원 배열에서는 0으로 채워주는 과정이 필요하고,
스택에 넣기 전에 최상위 값이 들어가야 하는 값과 동일하면 Clear 시켜주는 것을 유의해야 하겠습니다.
fun solution(board: Array<IntArray>, moves: IntArray): Int {
var res = 0
val stack = Stack<Int>()
val newBoard = mutableListOf<MutableList<Int>>()
board.forEach { newBoard.add(it.toMutableList()) }
fun getLines(index: Int): List<Int> {
return newBoard.map { it[index] }
}
moves.forEach {
val lines = getLines(it - 1)
val target = lines.firstOrNull { num -> num != 0 } ?: 0
if (target != 0) {
val pos = lines.indexOfFirst { value -> value == target }
newBoard[pos][it - 1] = 0
if (stack.isNotEmpty() && stack.peek() == target) {
stack.pop()
res += 2
} else {
stack.push(target)
}
}
}
return res
}
반응형