Next Closest Time问题及解法

问题描述:

Given a time represented in the format "HH:MM", form the next closest time by reusing the current digits. There is no limit on how many times a digit can be reused.

You may assume the given input string is always valid. For example, "01:34", "12:09" are all valid. "1:34", "12:9" are all invalid.

示例:

Input: "19:34"
Output: "19:39"
Explanation: The next closest time choosing from digits 1, 9, 3, 4, is 19:39, which occurs 5 minutes later.  It is not 19:33, because this occurs 23 hours and 59 minutes later.
Input: "23:59"
Output: "22:22"
Explanation: The next closest time choosing from digits 2, 3, 5, 9, is 22:22. It may be assumed that the returned time is next day's time since it is smaller than the input time numerically.

问题分析:

将time中的数字按升序存放的数组res中,分别对time的每一个数字time[i](i = 4,3,1,0)从后往前与res中的数进行比较,在res中找到第一个比time[i]中数字大的数s,将time[i] = s,i 之后的所有time中的数字,都置为res[0].


过程详见代码:

class Solution {
public:
    string nextClosestTime(string time) {
        vector<int> res{ time[0] - '0', time[1] - '0', time[3] - '0', time[4] - '0'};
		sort(res.begin(), res.end());
		for (int i = 0; i < 4; i++)
		{
			if (res[i] > time[4] - '0')
			{
				time[4] = res[i] + '0';
				return time;
			}
		}
		for (int i = 0; i < 4; i++)
		{
			if (res[i] > time[3] - '0' && res[i] < 6)
			{
				time[3] = res[i] + '0';
				time[4] = res[0] + '0';
				return time;
			}
		}
		for (int i = 0; i < 4; i++)
		{
			if (res[i] > time[1] - '0' && (time[0] - '0' < 2 || res[i] < 4))
			{
				time[1] = res[i] + '0';
				time[3] = res[0] + '0';
				time[4] = res[0] + '0';
				return time;
				
			}
		}
		for (int i = 0; i < 4; i++)
		{
			if (res[i] > time[0] - '0' && res[i] < 3)
			{
				time[0] = res[i] + '0';
				time[1] = res[0] + '0';
				time[3] = res[0] + '0';
				time[4] = res[0] + '0';
				return time;
			}
		}
		time[0] = res[0] + '0';
		time[1] = res[0] + '0';
		time[3] = res[0] + '0';
		time[4] = res[0] + '0';
		return time;
    }
};


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值