링크 : https://school.programmers.co.kr/learn/courses/30/lessons/118667
프로그래머스
SW개발자를 위한 평가, 교육, 채용까지 Total Solution을 제공하는 개발자 성장을 위한 베이스캠프
programmers.co.kr
문제 풀이
처음 풀었던 아래 코드로 70점이 나왔다.
import java.util.*;
class Solution {
public int solution(int[] queue1, int[] queue2) {
int total = 0;
int sum1 = 0;
Queue<Integer> q1 = new LinkedList<>();
Queue<Integer> q2 = new LinkedList<>();
for(int i=0; i<queue1.length; i++) {
q1.add(queue1[i]);
total += queue1[i];
sum1 += queue1[i];
q2.add(queue2[i]);
total += queue2[i];
}
if(total % 2 != 0) {
return -1;
}
total /= 2;
int cnt = 0;
while(cnt < queue1.length * 3) {
if(q1.isEmpty() || q2.isEmpty()) {
cnt = -1;
break;
}
if(sum1 > total) {
q2.add(q1.peek());
sum1 -= q1.poll();
} else if(sum1 == total) {
break;
} else if(sum1 < total) {
q1.add(q2.peek());
sum1 += q2.poll();
}
cnt += 1;
}
return cnt;
}
}

해결 1.
첫번째 문제점은 total과 sum1의 변수 자료형을 int로 둔 것이었다...
이를 수정한 후 테스트케이스 11번, 28번을 제외하고 통과하였다.
해결 2.
total이 짝수이고, while문의 루프를 끝까지 돌았음에도 합을 구할 수 없는 경우가 존재한다.
예를 들어 [1, 4]와 [3, 4]의 경우 -1이 리턴되어야 한다.
이를 걸러주기 위해 마지막에 다음과 같은 조건을 추가하여 분기 후 리턴하도록 수정하였다.
if(sum1 == total) {
return cnt;
} else {
return -1;
}
최종 코드는 다음과 같다.
import java.util.*;
class Solution {
public int solution(int[] queue1, int[] queue2) {
long total = 0;
long sum1 = 0;
Queue<Integer> q1 = new LinkedList<>();
Queue<Integer> q2 = new LinkedList<>();
for(int i=0; i<queue1.length; i++) {
q1.add(queue1[i]);
total += queue1[i];
sum1 += queue1[i];
q2.add(queue2[i]);
total += queue2[i];
}
if(total % 2 != 0) {
return -1;
}
total /= 2;
int cnt = 0;
while(cnt <= queue1.length * 3) {
if(q1.isEmpty() || q2.isEmpty()) {
cnt = -1;
break;
}
if(sum1 > total) {
q2.add(q1.peek());
sum1 -= q1.poll();
} else if(sum1 == total) {
break;
} else if(sum1 < total) {
q1.add(q2.peek());
sum1 += q2.poll();
}
cnt += 1;
}
if(sum1 == total) {
return cnt;
} else {
return -1;
}
}
}'알고리즘 > 프로그래머스' 카테고리의 다른 글
| [프로그래머스] 게임 맵 최단거리(Java) (0) | 2025.01.08 |
|---|---|
| [프로그래머스] 할인 행사(Java) (1) | 2025.01.05 |
| [프로그래머스] 네트워크(Java) (2) | 2024.11.20 |
| [프로그래머스] 연속 부분 수열 합의 개수(Java) (1) | 2024.11.20 |
| [프로그래머스] 디펜스 게임(Java) (3) | 2024.11.12 |