Skip to content

Latest commit

 

History

History
42 lines (36 loc) · 1.03 KB

539.最小时间差.md

File metadata and controls

42 lines (36 loc) · 1.03 KB

539.最小时间差

/*
 * @lc app=leetcode.cn id=539 lang=typescript
 *
 * [539] 最小时间差
 */

// @lc code=start
function findMinDifference(timePoints: string[]): number {}
// @lc code=end

解法 1: 排序

function findMinDifference(timePoints: string[]): number {
  const times = timePoints.sort((a, b) => (a > b ? 1 : -1)).map(s => s.split(':').map(Number))
  let min = Infinity,
    cur = times[times.length - 1]
  for (let i = 0; i < times.length; i++) {
    const next = times[i]
    const minute = Math.abs((next[0] - cur[0]) * 60 + (next[1] - cur[1]))
    min = Math.min(min, minute, 1440 - minute)
    cur = next
  }
  return min
}

Case

test.each([
  { input: { timePoints: ['00:00', '04:00', '22:00'] }, output: 120 },
  { input: { timePoints: ['23:59', '00:00'] }, output: 1 },
  { input: { timePoints: ['00:00', '23:59', '00:00'] }, output: 0 },
])('input: timePoints = $input.timePoints', ({ input: { timePoints }, output }) => {
  expect(findMinDifference(timePoints)).toEqual(output)
})