Minimum Time Difference问题及解法

问题描述:

Given a list of 24-hour clock time points in "Hour:Minutes" format, find the minimum minutes difference between any two time points in the list.

示例:

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

Note:

  1. The number of time points in the given list is at least 2 and won't exceed 20000.
  2. The input time is legal and ranges from 00:00 to 23:59.

问题分析:

将时间转换为整数值,然后升序排序,计算相邻数值之间的差值(最后一个和第一个算做系相邻元素),最小的差值即为答案。


过程详见代码:

class Solution {
public:
    int findMinDifference(vector<string>& timePoints) {
        sort(timePoints.begin(), timePoints.end());
		int mini = INT_MAX;
		int hour1 = stoi((timePoints[0]).substr(0, 2)),hour2;
		int minute1 = stoi((timePoints[0]).substr(3, 2)),minute2;
		for (int i = 1; i < timePoints.size(); i++)
		{
			hour2 = stoi((timePoints[i]).substr(0, 2));
			minute2 = stoi((timePoints[i]).substr(3, 2));
			mini = min(mini, (hour2 - hour1) * 60 + (minute2 - minute1));
			hour1 = hour2;
			minute1 = minute2;
		}
		int m = (23 - hour1) * 60 + (60 - minute1) ;
		hour1 = stoi((timePoints[0]).substr(0, 2));
		minute1 = stoi((timePoints[0]).substr(3, 2));
		m = m + hour1 * 60 + minute1;
		mini = min(mini, m);
		return mini;
    }
};


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值