미리수얌 블로그

Leetcode: Minimum Time Difference 본문

코딩문제풀이/Leetcode

Leetcode: Minimum Time Difference

미리수얌 2018. 10. 17. 10:56

Minimum Time Difference

시간이 hh:mm 형식으로 주어졌을때, 시간의 차이가 가장 적을 때의 값을 분으로 구하여라.
예: ["00:00", "00:15", "23:58", "00:25"] 답: 2. 23:58 분과 00:00 은 2분차이 임.
단, 리스트는 최소 길이가 2이고 시간은 00:00 부터 23:59 까지 가능함.

public int findMinDifference(List<String> timePoints) {
    List<Integer> minutes = new ArrayList<>();
    Set<Integer> added = new HashSet<>();
    for (String points: timePoints) {
        String[] times = points.split(":");
        int totalMinutes = Integer.parseInt(times[0]) * 60 + Integer.parseInt(times[1]);
        boolean add = added.add(totalMinutes);
        if (!add) return 0;
        minutes.add(totalMinutes);
    }
    Collections.sort(minutes);
    int minTimeDiff = Integer.MAX_VALUE;
    for (int i = 0; i < minutes.size() - 1; ++i) {
        int diff = minutes.get(i + 1) - minutes.get(i);
        minTimeDiff = Math.min(minTimeDiff, diff);
    }
    return Math.min(minTimeDiff, minutes.get(0) + 24 * 60 - minutes.get(minutes.size() - 1));
}

'코딩문제풀이 > Leetcode' 카테고리의 다른 글

Leetcode: Power of Four  (0) 2018.10.05
Leetcode: Power of Two  (0) 2018.10.05
Leetcode: Set Mismatch  (0) 2018.10.05
Leetcode: Diameter of Binary Tree  (0) 2018.09.29
Leetcode: String Compression  (0) 2018.09.29
Comments