✴️ 문제
https://school.programmers.co.kr/learn/courses/30/lessons/92341#qna
✴️ 문제 풀이
HashMap을 통해 차량 번호와 시간을 저장하는 방식을 이용해 해결했다.
우선 `map`은 입차인 경우 `(차량 번호, 입차 시간)`을 저장하기 위한 HashMap
`feeMap`은 최종적인 주차 시간을 저장하기 위해 `(차량 번호, 누적 시간)`을 저장한다.
- 입차인 경우 `map`에 `(차량 번호, 입차 시간)` 저장
- 출차인 경우
- 이미 `feeMap`에 존재한다면 `(feeMap의 값 + 출차 시간 + 입차 시간)`으로 값 갱신
- 존재하지 않는다면 `(출차시간 - 입차시간)`을 `feeMap`에 추가
- `map`에서 입차 기록 삭제
- `map`이 비어있지 않다면 입차만 하고 출차는 안한 차가 존재한다는 뜻이므로 23:59를 출차 시간으로 계산해 `feeMap`에 추가
- 차량 번호를 기준으로 오름차순 정렬
- `fees`를 통해 주차비 계산
의 과정으로 문제를 풀이한다.
이 문제에서 주의해야하는 점은 두 가지였다.
- 입차를 여러 번하는 차가 존재할 수 있다.
- 주차비를 계산하기 위해서 `Math.ceil`이라던가 `Double`로의 형변환이 필요하다.
** 만약에 이래도 계속 틀린다면 아래 테스트 케이스 한 번 시도해보시길...**
fees | records | result |
[180, 5000, 10, 600] | ["05:34 5961 IN", "06:34 5961 OUT", "07:34 5961 IN", "08:34 5961 OUT", "09:34 5961 IN", "10:34 5961 OUT", "11:34 5961 IN", "12:34 5961 OUT"] | [8600] |
[1, 10, 1, 11] | ["00:00 1234 IN", "00:02 1234 OUT"] | [21] |
✴️ 전체 코드(Java)
import java.util.*;
class Solution {
public int[] solution(int[] fees, String[] records) {
Map<String, Integer> feeMap = new HashMap<>(); // (차량 번호, 주차 시간) 저장
Map<String, Integer> map = new HashMap<>(); // (차량 번호, 입차 시간) 저장
for(int i = 0; i < records.length; i++){
String[] record = records[i].split(" ");
int time = getTime(record[0]);
String car = record[1];
String cmd = record[2];
if(cmd.equals("IN")){ // 입차인 경우
map.put(car, time);
}else{
int inTime = map.get(car);
int outTime = time;
map.remove(car);
if(feeMap.containsKey(car)){
feeMap.replace(car, feeMap.get(car) + outTime- inTime);
}else{
feeMap.put(car, outTime - inTime);
}
}
}
// 입차 기록만 있고 출차 기록이 없는 경우
if(!map.isEmpty()){
for(String carNum : map.keySet()){
feeMap.put(carNum, feeMap.getOrDefault(carNum, 0) + 23 * 60 + 59 - map.get(carNum));
}
}
// 차 번호 오름차순으로 정렬
Object[] sortKey = feeMap.keySet().toArray();
Arrays.sort(sortKey);
int[] answer = new int[sortKey.length];
// fees[0] : 기본 시간
// fees[1] : 기본 요금
// fees[2] : 단위 시간
// fees[3] : 단위 요금
for(int i = 0; i < answer.length; i++){
int time = feeMap.get(sortKey[i]); // 주차 시간
answer[i] = time > fees[0] ? fees[1] + (int)Math.ceil((time - fees[0])/ Double.valueOf(fees[2])) * fees[3] : fees[1];
}
return answer;
}
public int getTime(String time){
String[] times = time.split(":");
int hour = Integer.parseInt(times[0]) * 60;
int min = Integer.parseInt(times[1]);
return hour + min;
}
}
'코딩테스트 > 프로그래머스' 카테고리의 다른 글
[프로그래머스] 괄호 회전하기 (Lv.2) (0) | 2025.04.07 |
---|---|
[프로그래머스] 오픈채팅방 (Lv.2) (0) | 2025.04.05 |
[프로그래머스] 주식 가격 (Lv.2) (0) | 2025.04.02 |
[프로그래머스] 방문 길이 (Lv.2) (0) | 2025.04.01 |
[프로그래머스] 튜플 (Lv.2) (0) | 2025.03.29 |