返回介绍

solution / 0500-0599 / 0539.Minimum Time Difference / README

发布于 2024-06-17 01:03:59 字数 3472 浏览 0 评论 0 收藏 0

539. 最小时间差

English Version

题目描述

给定一个 24 小时制(小时:分钟 "HH:MM")的时间列表,找出列表中任意两个时间的最小时间差并以分钟数表示。

 

示例 1:

输入:timePoints = ["23:59","00:00"]
输出:1

示例 2:

输入:timePoints = ["00:00","23:59","00:00"]
输出:0

 

提示:

  • 2 <= timePoints.length <= 2 * 104
  • timePoints[i] 格式为 "HH:MM"

解法

方法一

class Solution:
  def findMinDifference(self, timePoints: List[str]) -> int:
    if len(timePoints) > 24 * 60:
      return 0
    mins = sorted(int(t[:2]) * 60 + int(t[3:]) for t in timePoints)
    mins.append(mins[0] + 24 * 60)
    res = mins[-1]
    for i in range(1, len(mins)):
      res = min(res, mins[i] - mins[i - 1])
    return res
class Solution {
  public int findMinDifference(List<String> timePoints) {
    if (timePoints.size() > 24 * 60) {
      return 0;
    }
    List<Integer> mins = new ArrayList<>();
    for (String t : timePoints) {
      String[] time = t.split(":");
      mins.add(Integer.parseInt(time[0]) * 60 + Integer.parseInt(time[1]));
    }
    Collections.sort(mins);
    mins.add(mins.get(0) + 24 * 60);
    int res = 24 * 60;
    for (int i = 1; i < mins.size(); ++i) {
      res = Math.min(res, mins.get(i) - mins.get(i - 1));
    }
    return res;
  }
}
class Solution {
public:
  int findMinDifference(vector<string>& timePoints) {
    if (timePoints.size() > 24 * 60)
      return 0;
    vector<int> mins;
    for (auto t : timePoints)
      mins.push_back(stoi(t.substr(0, 2)) * 60 + stoi(t.substr(3)));
    sort(mins.begin(), mins.end());
    mins.push_back(mins[0] + 24 * 60);
    int res = 24 * 60;
    for (int i = 1; i < mins.size(); ++i)
      res = min(res, mins[i] - mins[i - 1]);
    return res;
  }
};
func findMinDifference(timePoints []string) int {
  if len(timePoints) > 24*60 {
    return 0
  }
  var mins []int
  for _, t := range timePoints {
    time := strings.Split(t, ":")
    h, _ := strconv.Atoi(time[0])
    m, _ := strconv.Atoi(time[1])
    mins = append(mins, h*60+m)
  }
  sort.Ints(mins)
  mins = append(mins, mins[0]+24*60)
  res := 24 * 60
  for i := 1; i < len(mins); i++ {
    res = min(res, mins[i]-mins[i-1])
  }
  return res
}
function findMinDifference(timePoints: string[]): number {
  const mins = timePoints
    .map(item => Number(item.slice(0, 2)) * 60 + Number(item.slice(3, 5)))
    .sort((a, b) => a - b);
  const n = mins.length;
  let res = Infinity;
  for (let i = 0; i < n - 1; i++) {
    res = Math.min(res, mins[i + 1] - mins[i]);
  }

  const first = mins[0] + 24 * 60;
  const last = mins[n - 1];
  res = Math.min(res, first - last);

  return res;
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
    我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
    原文