///
Search

두 큐 합 같게 만들기

from collections import deque def solution(queue1, queue2): answer = -1 qsize = len(queue1) q1_sum = sum(queue1) q2_sum = sum(queue2) q1 = deque(queue1) q2 = deque(queue2) for i in range(0, 4*qsize): answer+=1 if q1_sum == q2_sum: return answer elif q1_sum < q2_sum: tmp = q2.popleft() q1.append(tmp) q1_sum += tmp q2_sum -= tmp else: tmp = q1.popleft() q2.append(tmp) q1_sum -= tmp q2_sum += tmp return -1
SQL
복사
질문
왜 qsize를 4배 해주는것인가
from collections import deque def solution(queue1, queue2): answer = -1 queue = queue1 + queue2 q1_sum = sum(queue1) target = (sum(queue1)+sum(queue2))//2 i, j = 0, len(queue1) while True: answer += 1 if q1_sum > target: q1_sum -= queue[i] i += 1 elif target > q1_sum: q1_sum += queue[j] j += 1 else: return answer if (i == j) or (j == len(queue)): return -1
Python
복사