본문 바로가기

LeetCode

539. Minimum Time Difference / TypeScript

Given a list of 24-hour clock time points in "HH:MM" format, return the minimum minutes difference between any two time-points in the list.

 

Example 1:

Input: timePoints = ["23:59","00:00"]
Output: 1

Example 2:

Input: timePoints = ["00:00","23:59","00:00"]
Output: 0

 

출처 : https://leetcode.com/problems/minimum-time-difference/description/

 

풀이

function findMinDifference(timePoints: string[]): number {
  
    timePoints.sort()
    const parsed = timePoints.map(time => parse(time))

    parsed.push(parsed[0] + 1440)

    let min = Infinity

    for (let i = 1; i < parsed.length; i++){
     min = Math.min(min, parsed[i] - parsed[i - 1])
    }

    return min
};

function parse (s: string) {

  const parsed = s.split(':')

  const hour = parseInt(parsed[0])
  const minute =  parseInt(parsed[1])

  return hour * 60 + minute
}

 

주어진 시간 목록(timePoints)에서 최소 시간 차이를 찾는 함수

 

parsed.push(parsed[0] + 1440)

 

  • 정렬된 배열의 첫 번째 시간에 1440분(24시간)을 더한 값을 배열의 끝에 추가.
  • 이는 첫 번째 시간과 마지막 시간의 차이를 고려하기 위함.
  • 예를 들어, "00:00"은 0분인데, 여기에 1440을 더해 1440분이 되어 배열의 끝에 추가 -> 23:59 분과 비교하면 1이 나와야하기 때문

["23:59", "00:00", "12:34", "08:45"]

  • ["23:59", "00:00", "12:34", "08:45"]를 사전순으로 정렬하면 ["00:00", "08:45", "12:34", "23:59"]
  • parse 함수는 주어진 "HH" 형식의 시간을 분 단위로 변환 [0, 525, 754, 1439]
  • 첫 번째 시간에 1440분(24시간)을 더한 값을 배열의 끝에 추가[0, 525, 754, 1439, 1440]
  • 최종적으로 최소 시간 차이인 1분을 반환