[코딩테스트] 프로그래머스 - 주차 요금 계산(Java)

proman·2022년 9월 17일
0

Coding-Test

목록 보기
14/21
post-thumbnail

😽 설명

레벨: 2
언어: 자바(Java)

🐹 느낀점

해당 문제는 알고리즘 활용보단 자료구조 활용하는방식인 문제라고 생각합니다
난이도도 사실상 어렵다기보단 계산으로 인한 코드가 많은 문제라고 볼수있습니다.

저의 풀이방법은
1. records 배열에 있는 차량별 입출입 기록들을 queue에 넣어서 순차처리예정이며
2. 추출해낸 차량별 입출이 기록들을 queue에서 뽑아내어 입출입 시간간격을 구하고(출입 없을시 23:59 값 대입)
3. 입출입 시간간격에 따른 계산 진행
4. 차량번호 낮은순으로 비용값 배열 반환
이런 방식으로 풀었습니다

가장 좋아요 많이 받은 코드를 분석해보면
1. records 배열에 있는 값 추출
2. 제가 했던방식과는 별개로 Queue에 넣지않고 +- 바로 구해서 넣는방식
3. 계산비용을 구하기 위한 루프 및 계산처리로 배열반환

최종적으로 느낀게 queue를 안사용하고 풀수있었으며, 가장 좋아요 많이 받은 코드에서 map에서 for문 다시 돌리기보단 제가 했던 stream으로 반환식으로 했으면 좀 더 보기 좋지 않았을까 생각해봅니당~~

🦥 내가 작성한 코드

import java.util.*;

class Solution {
    private static final String IN = "IN", OUT = "OUT";
    
    static class InOut{
        int time;
        String type;
        
        public InOut(String time, String type) {
            String[] hourMin = time.split(":");
            this.time = Integer.valueOf(hourMin[0]) * 60 + Integer.valueOf(hourMin[1]);
            this.type = type;
        }
    }
    
    public int[] solution(int[] fees, String[] records) {
        Map<String, Queue<InOut>> map = new HashMap<>();
        
        for(String record: records) {
            String[] recordArr = record.split(" ");
            Queue<InOut> queue = map.getOrDefault(recordArr[1], new LinkedList<InOut>());
            queue.offer(new InOut(recordArr[0], recordArr[2]));
            map.put(recordArr[1], queue);
        }
        
        Map<String, Integer> resultMap = new HashMap<>();
        for(String carNum: map.keySet()) {
            Queue<InOut> queue = map.get(carNum);
            int range = 0;
            while(!queue.isEmpty()) {
                InOut in = queue.poll();
                    
                InOut out = queue.isEmpty()
                    ? new InOut("23:59", OUT)
                    : queue.poll();
                
                range += out.time - in.time;
            }

            int pay = resultMap.getOrDefault(carNum, 0);
                
            range = range - fees[0];
            pay += fees[1];

            if(range > 0) {
                pay += Math.ceil((double) range / fees[2]) * fees[3];
            };

            resultMap.put(carNum, pay);
        }
                
        return resultMap.keySet()
            .stream()
            .sorted()
            .map(key -> resultMap.get(key))
            .mapToInt(val -> val.intValue())
            .toArray();
    }
}

🦎 좋아요 가장 많이받은 코드

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;
    }
}

0개의 댓글