Next Closest Time问题及解法

来源:互联网 发布:java log4j jar下载 编辑:程序博客网 时间:2024/06/05 19:23

问题描述:

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;    }};


原创粉丝点击