programmers_두 큐 합 같게 만들기_java
2023. 4. 17. 10:46ㆍAlgorithm/Programmers
728x90
https://school.programmers.co.kr/learn/courses/30/lessons/118667#
import java.util.*;
class Solution {
public int solution(int[] queue1, int[] queue2) {
int answer = 0;
int queueSize = queue1.length;
long queue1Sum = 0;
long queue2Sum = 0;
Queue<Integer> q1 = new LinkedList<>();
Queue<Integer> q2 = new LinkedList<>();
for(int i = 0; i< queueSize; i++){
queue1Sum += queue1[i];
q1.offer(queue1[i]);
queue2Sum += queue2[i];
q2.offer(queue2[i]);
}
while(queue1Sum != queue2Sum){
if(queue1Sum > queue2Sum){
int tmp = q1.poll();
q2.offer(tmp);
queue1Sum -= tmp;
queue2Sum += tmp;
}else{
int tmp = q2.poll();
q1.offer(tmp);
queue2Sum -= tmp;
queue1Sum += tmp;
}
answer++;
if(answer > queueSize*4){
answer = -1;
break;
}
}
return answer;
}
}
'Algorithm > Programmers' 카테고리의 다른 글
programmers_괄호 변환_java (0) | 2023.04.22 |
---|---|
programmers_택배상자_java (0) | 2023.04.17 |
programmers_메뉴 리뉴얼_java (0) | 2023.04.17 |
programmers_삼각 달팽이_java (0) | 2023.04.16 |
programmers_124 나라의 숫자_java (0) | 2023.04.16 |