눈송이의 개발생활
[Programmers Lv.1]크레인 인형 뽑기 (Python) 본문
문제
https://programmers.co.kr/learn/courses/30/lessons/64061
내 코드
def solution(board, moves):
answer = 0
stack = []
for i in range(len(moves)):
col = moves[i] - 1
for j in range(len(board)):
if board[j][col] != 0:
out = board[j][col]
board[j][col] = 0
stack.append(out)
if len(stack) >= 2:
if stack[-1] == stack[-2]:
stack.pop()
stack.pop()
answer += 2
break
return answer
다른 사람 풀이
def solution(board, moves):
stacklist = []
answer = 0
for i in moves:
for j in range(len(board)):
if board[j][i-1] != 0:
stacklist.append(board[j][i-1])
board[j][i-1] = 0
if len(stacklist) > 1:
if stacklist[-1] == stacklist[-2]:
stacklist.pop(-1)
stacklist.pop(-1)
answer += 2
break
return answer
해결 방법
문제가 길고 복잡해(?) 보여서 약간 겁먹었는데 생각보다 금방 풀 수 있었다.
각 줄을 col이라는 변수로 놓고 맨 위에서 부터(0이 아닌 숫자를 만나면) 0으로 바꿔주었다.
인형을 뽑아서 저장해두는 stack에 인형이 2개 이상 있으면 가장 위에 있는 2개를 본다.
2개가 동일하면 stack에서 pop하고 뽑은 인형 수에 2를 더한다.
숫자를 찾는 과정을 수행하면 그 다음 row를 볼 필요가 없기 때문에 반복문에서 break로 나와준다.
'Algorithm > Programmers' 카테고리의 다른 글
[Programmers Lv.1]실패율 (Python) (0) | 2022.03.28 |
---|---|
[Programmers Lv.1]신고 결과 받기 (Python) (0) | 2022.03.26 |
[Programmers Lv.1]키패드 누르기 (Python) (0) | 2022.03.23 |
[Programmers Lv.1]숫자 문자열과 영단어 (Python) (0) | 2022.03.23 |
[Programmers Lv.1]콜라츠 추측 & 최대공약수와 최소공배수 (Python) (0) | 2022.03.10 |
Comments