주차 요금 계산

문제 링크 : https://school.programmers.co.kr/learn/courses/30/lessons/92341

접근 방식

크게 4번을 통해 계산하려고 했다.

  • 기록을 통해 IN은 입차 OUT은 출차, 출차의 경우 Map에서 번호와 일치하는 차량의 입차 시간을 받아온다.
  • 출차와 입차 시간을 각각 분으로 환산해서 주차 시간을 계산한다.
  • 다시 Map을 돌면서 시간이 OUT이 아닌경우, (위에서 출차 시에, 데이터를 OUT을 넣음) 23:59 - 입차시간을 통해 주차시간을 알아낸다.
  • 모든 주차시간의 계산이 끝났음으로, 요금표를 통해 요금을 계산해서 리턴한다.

결과

소스 코드

import java.util.*;

class Solution {
    public int[] solution(int[] fees, String[] records) {
        Map<String, String> map = new HashMap<>();
        Map<Integer, Integer> sum = new TreeMap<>();

        for(String record:records){
            String tmp[] = record.split(" ");
            if (tmp[2].equals("IN")){
                map.put(tmp[1], tmp[0]);
            }else {
                String in = map.get(tmp[1]);
                map.put(tmp[1], "OUT");
                int time = calc(in, tmp[0]);
                int t = sum.getOrDefault(Integer.parseInt(tmp[1]), 0);
                sum.put(Integer.parseInt(tmp[1]), time+t);
            }
        }
        for(String m:map.keySet()){
            if(!map.get(m).equals("OUT")){
                int time = calc(map.get(m), "23:59");
                int t = sum.getOrDefault(Integer.parseInt(m), 0);
                sum.put(Integer.parseInt(m), time+t);
            }
        }

        return calFee(sum, fees);
    }

    private int calc(String in, String out){
        int inTime[] = Arrays.stream(in.split(":")).mapToInt(a->Integer.parseInt(a)).toArray();
        int outTime[] = Arrays.stream(out.split(":")).mapToInt(a->Integer.parseInt(a)).toArray();
        int time = (outTime[0]*60 + outTime[1]) - (inTime[0] * 60 + inTime[1]);
        return time;
    }

    private int[] calFee(Map<Integer, Integer> map, int[] fees){
        List<Integer> list = new ArrayList<>();
        for(int m:map.keySet()){
            int s = (int) Math.ceil((double)(map.get(m)-fees[0])/(double)fees[2]);
            int tmp = map.get(m)<=fees[0] ? fees[1] : fees[1]+s*fees[3];
            list.add(tmp);
        }

        return list.stream().mapToInt(a->a).toArray();
    }
}

일단 문제를 푸는 것에 집중을 하다보니, 코드가 좀 길어졌다.

최적화

현재 Map 자료구조를 두 개 이용해서, 하나는 자동차의 출입관리, 나머지 하나는 자동차의 주차시간 관리에 사용하고 있다.

몇 개 코드와 카카오 정식 해설을 보니 int 배열을 통해 보다 쉽게 관리할 수 있음을 알게 되었다.

알게 된 점

없음.