PROGRAMMERS/KAKAO

[프로그래머스] [JAVA] [Level 2] [2022 KAKAO BLIND RECRUITMENT] 주차 요금 계산

c0mmedes 2022. 10. 21. 13:56

문제 설명


제한사항


입출력 예


import java.util.*;

class Solution {
    // (String)시간을 (Int)min으로 바꿔주는 메소드
    public int getMin(String time){
        // ex) 15:30 t[0] = 15, t[1] = 30 
        String t[] = time.split(":");
        // ex) int형으로 변환후 15 * 60 + 30
        return Integer.valueOf(t[0])*60 + Integer.valueOf(t[1]);
    }
    
    public int[] solution(int[] fees, String[] records) {
            
        Map<String, Integer> parking = new HashMap<>(); // 현재 파킹 중인 차들     
        Map<String, Integer> times = new HashMap<>(); // 차들의 누적 파킹 시간
        List<String> cars = new ArrayList<>(); // 차들 list
        
        for(String record : records){
            String rc[] = record.split(" "); // records 배열의 첫번째 원소를 공백을 기준으로 잘라서 rc 배열에 넣기
            int time = getMin(rc[0]); // 시간 05:34
            String car = rc[1]; // 차량번호 5961
            
            // 차들(cars) list에 차량번호가 등록되어 있지 않다면(새로운 차량일 때)
            if(!cars.contains(car)){
                cars.add(car); // 차량 등록
                times.put(car, 0); // times Map에 차량 등록
            }
            
            // 파킹이 되어있다면(출차)
            if(parking.containsKey(car)){
                // times Map에 전에 등록된 시간에 새로운 누적시간 더해서 등록
                times.put(car, times.get(car) + (time-parking.get(car))); 
                // 나갔으니 삭제 
                parking.remove(car); 
            // 입차  
            } else {
                parking.put(car, time);
            }
        }
        
        int[] answer = new int[cars.size()];
        Collections.sort(cars); // 차량번호별로 정렬
        
        for(int i=0; i<cars.size(); i++){
            answer[i] = fees[1]; // 기본요금
            String car = cars.get(i);
            int time = times.get(car) - fees[0]; // 누적 시간에서 기본 시간 뺴주기
            
            // 출차가 안되어 있다면(23:59)
            if(parking.containsKey(car)) {
                time += getMin("23:59")-parking.get(car);
            }
            
            // 요금 계산
            if(time>0) {
                answer[i] += (Math.ceil(time/(fees[2]*1.0))*fees[3]);
            }
        }
            
        return answer; 
    }
}

참조 https://velog.io/@ujone/%ED%94%84%EB%A1%9C%EA%B7%B8%EB%9E%98%EB%A8%B8%EC%8A%A4-%EC%A3%BC%EC%B0%A8-%EC%9A%94%EA%B8%88-%EA%B3%84%EC%82%B0-JAVA