Search
Duplicate
📒

[Programmers] 09-2. 주차 요금 계산

상태
완료
수업
Algorithm Solving
주제
Programmers
4 more properties
참고

문제해설

NOTE
입력값 ⇒ 정수배열(가격 표), 문자배열 (주차장 입/출 기록)
출력값 ⇒ 가격표와, 입출기록을 통한 요금계산

문제 로직고민

NOTE
각 자동차의 In - Out의 값을 저장해줄 Map과 총 주차시간을 담을 Map 2개를 선언한다.
In에는 들어온 시간을 기록해준다. Out의 경우에는 In의 시간과 비교해서 총주차시간에 더해준다.
만약 Out의 기록이 없다면, 23:59의 Out으로 생각해서 해결한다.
자동차 번호순으로 값을 뽑아야하므로 TreeMap을 이용한다.

작성코드

NOTE
import java.util.*; class Solution { public int[] solution(int[] fees, String[] records) { HashMap<String, Integer> map = new HashMap(); TreeMap<String, Integer> map2 = new TreeMap(); // 주차기록 계산 for(String record : records){ String[] r = record.split(" "); if(r[2].equals("IN")){ map.put(r[1], timeToMinute(r[0])); } else{ int inTime = map.get(r[1]); int outTime = timeToMinute(r[0]); int prevTime = map2.getOrDefault(r[1], 0); map2.put(r[1], prevTime + (outTime - inTime)); map.remove(r[1]); } } // 자정까지 나가지 않은 차 계산 for(Map.Entry<String, Integer> e : map.entrySet()){ int prevTime = map2.getOrDefault(e.getKey(), 0); map2.put(e.getKey(), prevTime + (timeToMinute("23:59") - e.getValue())); } // 가격계산 int[] answer = new int[map2.size()]; int idx = 0; for(Map.Entry<String, Integer> e : map2.entrySet()){ int time = e.getValue(); int money = 0; if(time <= fees[0]) money = fees[1]; else money = fees[1] + (int)Math.ceil((time-fees[0])/ (double) fees[2]) * fees[3]; answer[idx++] = money; } return answer; } private int timeToMinute(String time){ String[] t = time.split(":"); return Integer.parseInt(t[0]) * 60 + Integer.parseInt(t[1]); } }
Java
복사

다른사람 풀이

NOTE
import java.util.*; class Solution { public int timeToInt(String time) { String temp[] = time.split(":"); return Integer.parseInt(temp[0])*60 + Integer.parseInt(temp[1]); } public int[] solution(int[] fees, String[] records) { TreeMap<String, Integer> map = new TreeMap<>(); for(String record : records) { String temp[] = record.split(" "); int time = temp[2].equals("IN") ? -1 : 1; time *= timeToInt(temp[0]); map.put(temp[1], map.getOrDefault(temp[1], 0) + time); } int idx = 0, ans[] = new int[map.size()]; for(int time : map.values()) { if(time < 1) time += 1439; time -= fees[0]; int cost = fees[1]; if(time > 0) cost += (time%fees[2] == 0 ? time/fees[2] : time/fees[2]+1)*fees[3]; ans[idx++] = cost; } return ans; } }
Java
복사
TreeMap을 통한 정렬은 동일하나, Map을 2개 사용하지 않고, -+를 통해서 하나로 통합한게 인상깊다.