[프로그래머스] 주차 요금 계산(Java, 자바)

giggle·2023년 10월 10일
0

문제

주차 요금 계산


📌 아이디어

HashMap을 중점적으로 활용해 문제를 해결했습니다.

입차와 출차 두 가지 경우에서 사용할 HashMap을 만든 후 입/출차 기록을 탐색하며 입차인 경우는 현재 시간을 저장합니다. 또한, 출차인 경우에는 입차 시간과 현재 시간을 비교하여 누적합을 진행합니다.

모든 기록을 탐색 후 혹여나 마지막 시간에(23:59)에 입차되는 경우를 고려해 HashMap을 탐색 후 최종 누적합을 진행합니다.

그 후 차 번호 순서대로 정렬을 진행하고, 순서에 따른 주차 금액을 계산하여 정답을 도출합니다.

중심코드

// 입차인 경우
if (io.equals("IN")) {
	map1.put(car, time);
} 
// 출차인 경우
else {               
	// 입차 내역을 뽑고 입차값을 삭제
    int carTime1 = map1.get(car);
    map1.remove(car);
    // 출차 내역이 있는 경우는 누적합
    if (map2.containsKey(car)) {
        int carTime2 = map2.get(car);
        map2.replace(car, carTime2 + time - carTime1);    
    } 
    // 출차 내역이 없는 경우는 새로 갱신
    else {
        map2.put(car, time - carTime1);
    }   
}

📌 코드

import java.util.*;

/*
** HashMap을 통해 차에 대한 사용 시간 정리
** 그 후 HashMap을 탐색하고 해당시간에 대한 연산 진행
*/
class Solution {
    public int[] solution(int[] fees, String[] records) {
        int[] answer = {};
        Map<String, Integer> map1 = new HashMap<String, Integer>();
        Map<String, Integer> map2 = new HashMap<String, Integer>();
        
        int baseTime = fees[0];
        int baseFee = fees[1];
        int partTime = fees[2];
        int partFee = fees[3];
        
        for (String record : records) {
            String[] tmp = record.split(" ");
            int time = getRealTime(tmp[0]);
            String car = tmp[1];
            String io = tmp[2];
            
            if (io.equals("IN")) {
                map1.put(car, time);
            } else {
                int carTime1 = map1.get(car);
                map1.remove(car);
                if (map2.containsKey(car)) {
                    int carTime2 = map2.get(car);
                    map2.replace(car, carTime2 + time - carTime1);    
                } else {
                    map2.put(car, time - carTime1);
                }   
            }
        }
        int lastTime = 1439;
        for (String car : map1.keySet()) {
            int carTime1 = map1.get(car);
            if (map2.containsKey(car)) {
                    int carTime2 = map2.get(car);
                    map2.replace(car, carTime2 + lastTime - carTime1);    
                } else {
                    map2.put(car, lastTime - carTime1);
            }   
        }
        Object[] sortKey = map2.keySet().toArray();	//차 번호 순서대로 정렬
		Arrays.sort(sortKey);
        answer = new int[sortKey.length];

        for (int i = 0; i<answer.length; i++) {
            int result = baseFee;
            String car = String.valueOf(sortKey[i]);
            
            int val = map2.get(car);
            if (val > baseTime) {
                result = (int) (baseFee + Math.ceil((double)(val-baseTime)/partTime) * partFee);
            }
            answer[i] = result;
        }
        
        return answer;
    }
    
    public int getRealTime(String time) {
        String[] tmp = time.split(":");
        int hour = Integer.parseInt(tmp[0]) * 60;
        int minute = Integer.parseInt(tmp[1]);
        return hour + minute;
    }
}

✏️ TIP

1 . HashMap을 활용한 문제 풀이였기 때문에 HashMap에 대한 내용을 상기 시킬 필요가 있었습니다.(put, remove, containsKey, replace, keySet)
2. Key를 기준으로 HashMap 정렬하기 -> Object[] sortKey = map2.keySet().toArray();
3. 올림을 적절하게 활용하여 문제를 해결해야 합니다. -> result = (int) (baseFee + Math.ceil((double)(val-baseTime)/partTime) * partFee);


피드백 및 개선점은 댓글을 통해 알려주세요😊

profile
배움을 글로 기록하는 개발자가 되겠습니다.

0개의 댓글