프로그래밍 공방

[프로그래머스] 셔틀버스 본문

개발/문제해결

[프로그래머스] 셔틀버스

hyosupsong 2021. 1. 23. 02:14

문제

programmers.co.kr/learn/courses/30/lessons/17678

 

코딩테스트 연습 - [1차] 셔틀버스

10 60 45 [23:59,23:59, 23:59, 23:59, 23:59, 23:59, 23:59, 23:59, 23:59, 23:59, 23:59, 23:59, 23:59, 23:59, 23:59, 23:59] 18:00

programmers.co.kr

문제해결방법

크게 착각을 해서 이 문제를 푸는데 엄청 헤맸다.

예를들어 버스가 두 대 온다면 첫 번째 버스 이전에 도착하는 크루들 중에 첫 번째 버스에 못 타고 두 번째 버스에 탈 수도 있는데 이 크루들을 계산을 안해줘서 계속 틀렸다.

기본 아이디어는 아래와 같았다.

1. 셔틀 버스가 도착하는 시간을 기준으로 더 일찍 도착하는 크루들을 세준다.

2. 세다가 정원만큼 사람이 오면 그 다음 사람부터는 다음 버스에 탄다고 생각하고 1번 과정을 반복한다.

3. 셔틀 버스가 도착하는 모든 시간에 위 과정을 해주면 마지막에 탈 수 있는 사람 혹은 마지막 버스가 도착했을 때 빈 자리가 생기는지 알 수 있다.

4. 빈 자리가 생긴다면 (셔틀이 도착하는 마지막 시간)이 가장 늦은 시간이 되고 빈 자리가 없다면 (마지막 타는 크루가 도착하는 시간 - 1) 이 답이 된다.

코드

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
package Programmers;
 
import java.util.Arrays;
 
public class Solution_셔틀버스 {
 
    public static int timeToIndex(String time) {
        String[] s = time.split(":");
        int hour = Integer.parseInt(s[0]);
        int minute = Integer.parseInt(s[1]);
        return hour*60 + minute;
    }
 
    public static String solution(int n, int t, int m, String[] timetable) {
        String answer = "";
        int answerTime = 0;
        int[] arrived = new int[n];
        int[] times = new int[timetable.length];
        arrived[0= timeToIndex("09:00");
        for(int i=1; i<arrived.length; i++) arrived[i] = arrived[i-1]+t;
        for(int i=0; i<times.length; i++) times[i] = timeToIndex(timetable[i]);
        Arrays.sort(times);
        int waitNum = 0;
        int index = 0;
        for(int i=0; i<arrived.length; i++) {
            waitNum = 0;
            while(index<times.length && times[index]<=arrived[i]) {
                waitNum+=1;
                if(waitNum==m) {
                    index++;
                    break;
                }
                index++;
            }
        }
        if(waitNum<m) answerTime = arrived[n-1];
        else answerTime = times[index-1]-1;
        String hours = answerTime/60<10?"0"+answerTime/60:answerTime/60+"";
        String minutes = answerTime%60<10?"0"+answerTime%60:answerTime%60+"";
        answer = hours+":"+minutes;
        return answer;
    }
    
    public static void main(String[] args) {
        int n = 2;
        int t = 10;
        int m = 2;
        String[] timetable = {"09:10""09:09""08:00"};
        System.out.println(solution(n, t, m, timetable));
    }
}
cs


코드에 대한 피드백이나 더 좋은 아이디어는 언제나 환영입니다.

'개발 > 문제해결' 카테고리의 다른 글

[백준] 1766번 : 문제집  (0) 2021.01.26
OSI 7 Layer  (0) 2021.01.24
[프로그래머스] 가사 검색  (0) 2021.01.21
[프로그래머스] 베스트앨범  (0) 2021.01.20
[프로그래머스] 괄호 변환  (0) 2021.01.20