728x90
반응형
728x90
[Programmers] 택배 상자 꺼내기 - LV 1
접근
- 계산?
풀이
코드챌린지 2차 예선 문제로 택배 상자를 요구하는 순서로 쌓아 위에서부터 상자를 뺄 때 총 몇 개의 상자를 빼야 하는지 구하는 문제이다. 상자는 지그재그로 쌓기 때문에 꺼내야 하는 상자의 꼭대기엔 몇 개의 상자가 존재하는지 알 수 없다. 단순하게 일일이 상자를 다 쌓아보고 풀어도 될 거 같지만 단순하게 위의 상자만 빼기 때문에 계산을 통해 구해질 거 같아 해 봤다.
public int solution(int n, int w, int num) {
int totalLevel = n / w;
if (n % w > 0) totalLevel++;
int targetLevel = num / w;
if(num % w > 0) targetLevel++;
if(totalLevel == targetLevel) return 1;
boolean isTopReverse = totalLevel % 2 == 0;
boolean isTargetReverse = targetLevel % 2 == 0;
상자의 총개수를 나누어 상자가 몇 층 쌓여있는지 계산하고 목표 상자가 몇 층에 있는지 구해 차를 구해주면 꺼내야 할 상자의 개수가 나올 거 같았다. 상자가 쌓아진 방향은 1층 즉 홀수 층은 정방향 짝수 층은 역방향이었는데 목표 상자가 위치한 층과 꼭대기 층의 방향을 비교해 구해야 한다.
int targetLocation = num % w;
if (targetLocation == 0) {
if(!isTargetReverse) targetLocation = 1;
else targetLocation = w;
}
int topLocation = n % w;
if (isTargetReverse == isTopReverse) {
if (topLocation == 0 || topLocation >= targetLocation) {
return totalLevel - targetLevel + 1;
} else {
return totalLevel - targetLevel;
}
} else {
if (topLocation == 0 || w - topLocation <= targetLocation) {
return totalLevel - targetLevel + 1;
} else {
return totalLevel - targetLevel;
}
}
}
각 상자의 위치는 나머지를 통해 구했고 나머지가 0이라면 해당 층의 끝부분으로 정방향이라면 w 역방향이라면 첫 번째인 1로 바꿔줬다. 그리고 각 방향에 따라 구해주는데 꼭대기층의 상자가 가득 차있는 상태라면 단순하게 전체층 - 목표층을 해주면 된다 + 1은 목표 상자를 꺼내는 것도 개수로 카운트 시켜야 하기 때문에 해주는 것이다. 서로 방향이 다른 경우에는 꼭대기 층의 상자가 목표 상자 위를 덮고 있는지 체크하고 각각 개수를 반환해 주었다.
1-index 방식으로 상자의 위치를 1부터 계산했는데 상자의 개수와 목표 상자 번호를 1씩 빼서 인덱스 형태로 계산을 하면 0에 대한 처리를 덜 해도 되기 때문에 더 편하게 풀 수 있다.
전체 코드
class Solution {
public int solution(int n, int w, int num) {
int totalLevel = n / w;
if (n % w > 0) totalLevel++;
int targetLevel = num / w;
if(num % w > 0) targetLevel++;
if(totalLevel == targetLevel) return 1;
boolean isTopReverse = totalLevel % 2 == 0;
boolean isTargetReverse = targetLevel % 2 == 0;
int targetLocation = num % w;
if (targetLocation == 0) {
if(!isTargetReverse) targetLocation = 1;
else targetLocation = w;
}
int topLocation = n % w;
if (isTargetReverse == isTopReverse) {
if (topLocation == 0 || topLocation >= targetLocation) {
return totalLevel - targetLevel + 1;
} else {
return totalLevel - targetLevel;
}
} else {
if (topLocation == 0 || w - topLocation <= targetLocation) {
return totalLevel - targetLevel + 1;
} else {
return totalLevel - targetLevel;
}
}
}
}
728x90
'알고리즘 > 코딩테스트-Programmers' 카테고리의 다른 글
[Programmers] 완전범죄 JAVA (0) | 2025.04.14 |
---|---|
[Programmers] 서버 증설 횟수 JAVA (0) | 2025.03.19 |
[Programmers] 지게차와 크레인 JAVA (0) | 2025.03.07 |
[Programmers] 비밀 코드 해독 JAVA (0) | 2025.03.06 |
[Programmers] 유연근무제 JAVA (1) | 2025.03.05 |