풀이 방법✏️
- 첫 번째 큐와 두 번째 큐의 초기 상태 및 원소의 총 합을 저장
- 더 큰 큐에서 원소 추출
- 더 작은 큐에서 원소 추출
- 2번 과정에서 추출한 원소를 총합이 더 작은 큐에 삽입
- 3번 과정에서 추출한 원소를 총합이 더 큰 큐에 삽입
- 2~5번 과정을 두 큐의 합이 같아질 때 까지 반복
- 스왑한 횟수가 큐의 길이 * 2 + 1 보다 큰 경우 반복을 멈춤
소스 코드(feat. 알찬 주석)⌨️
import java.util.*;
class Solution {
static Queue<Integer> que1 = new ArrayDeque();
static Queue<Integer> que2 = new ArrayDeque();
long sum1, sum2;
int swapCnt;
public int solution(int[] queue1, int[] queue2) {
for(int i=0; i<queue1.length; i++){
que1.offer(queue1[i]);
que2.offer(queue2[i]);
sum1 += queue1[i];
sum2 += queue2[i];
}
while(sum1 != sum2){
if(swapCnt > queue1.length * 2 + 1){
swapCnt = -1;
break;
}
if(sum1 > sum2){
int temp = que1.poll();
sum1 -= temp;
que2.offer(temp);
sum2 += temp;
swapCnt++;
continue;
}
if(sum1 < sum2){
int temp = que2.poll();
sum2 -= temp;
que1.offer(temp);
sum1 += temp;
}
swapCnt++;
}
return swapCnt;
}
}