알고리즘/구현
파이썬 | 프로그래머스 | 숫자 게임
cha-n
2020. 11. 5. 00:55
solution 1 : 배열 이용 → 시간 초과
def solution(A, B):
A = sorted(A, reverse=True)
B = sorted(B, reverse=True)
score = 0
i, j = 0, 0
while i < len(A):
if A[i] < B[i]:
score += 1
i += 1
j += 1
else:
i += 1
return score
solution 2 : 힙 이용
최대 힙 : heapq.heappush(heap, (-n, n)) --> -n : 우선순위
import heapq
def solution(A, B):
heapA = []
heapB = []
for i in range(len(A)):
heapq.heappush(heapA, (-A[i], A[i]))
heapq.heappush(heapB, (-B[i], B[i]))
print(heapA[0][0])
score = 0
for i in range(len(A)):
if heapA[0][1] < heapB[0][1]:
score += 1
heapq.heappop(heapA)
heapq.heappop(heapB)
else:
heapq.heappop(heapA)
return score
문제 출처 programmers.co.kr/learn/courses/30/lessons/12987