[프로그래머스] 주차 요금 계산(92341)

lhs's avatar
Nov 28, 2024
[프로그래머스] 주차 요금 계산(92341)
 

1. 문제 풀이 아이디어

  • Map을 사용하여 시간을 저장하면 문제를 해결할 수 있다.

2. 나의 정답 코드

class Solution { public int[] solution(int[] fees, String[] records) { Map<String, Integer> time = new HashMap<>(); Map<String, Integer> alltime = new TreeMap<>(); for (String record : records) { String[] split = record.split(" "); String[] split2 = split[0].split(":"); int t = Integer.parseInt(split2[0]) * 60 + Integer.parseInt(split2[1]); if (split[2].length() == 2) { time.put(split[1], t); } else { alltime.put(split[1], alltime.getOrDefault(split[1], 0) + t - time.get(split[1])); time.remove(split[1]); } } for (Map.Entry<String, Integer> entry : time.entrySet()) { alltime.put(entry.getKey(), alltime.getOrDefault(entry.getKey(), 0) + 1439 - entry.getValue()); } int[] answer = new int[alltime.size()]; int i = 0; for (int t : alltime.values()) { int it = Math.max(0, (t - fees[0] + fees[2] - 1) / fees[2]); answer[i] = fees[1] + it * fees[3]; i++; } return answer; } }

3. 정리

  • alltime 맵은 차량 번호를 정렬하기 위해 TreeMap을 사용한다.
  • time 맵은 입차 시간을 시 * 60 + 분으로 변환해 저장한다.
  • alltime 맵은 출차 시점에서 현재 시간에서 time 맵의 시간을 빼고, 이를 누적하여 저장한다.
  • records 배열을 모두 순회한 후, 남아 있는 차량(출차 기록이 없는 경우)은 23:59(1439분)에서 입차 시간을 뺀 값을 alltime 맵에 추가한다.
  • alltime 맵의 값을 순회하며, 주어진 요금 체계를 기반으로 주차 요금을 계산하고 결과 배열에 저장한다.
Share article

LHS's Study Space