C ++中的下一个最近时间
假设我们有一个以“HH:MM”格式表示的时间,我们必须通过重用当前数字来生成下一个最接近的时间。我们可以无限制地使用该数字。
因此,如果输入像“19:34”,则输出将是“19:39”,因为从数字1、9、3、4选择的下一个最接近的时间是19:39。不是19:33,因为这发生在23小时59分钟之后。
为了解决这个问题,我们将遵循以下步骤-
定义一个函数eval(),它将取x,
a:=将x[0]转换为字符串
a:=a+x[1]
b:=将x[2]转换为字符串
b:=b+x[3]
返回a作为整数*60+b作为整数
从主要方法中执行以下操作-
ret:=空字符串
temp:=空字符串
差异:=inf
定义数组时间
在时间结束时插入t[0]
在时间结束时插入t[1]
在时间结束时插入t[3]
在时间结束时插入t[4]
n:=时间大小
src:=空字符串
temp1:=空字符串
temp2:=空字符串
对于初始化i:=0,当i<n时,更新(将i增加1),执行-
src:=src+时间[i]
对于初始化i:=0,当i<n时,更新(将i增加1),执行-
对于初始化k:=0,当k<n时,更新(将k增加1),-
差异:=newDiff
ret:=temp1+“:”+temp2
newDiff:=newDiff+(60*24)
忽略以下部分,跳至下一个迭代
忽略以下部分,跳至下一个迭代
对于初始化l:=0,当l<n时,更新(将l增加1),执行-
temp1:=时间[i]
temp1:=temp1+时间[j]
temp2:=时间[k]
temp2:=temp2+时间[l]
如果temp1作为数字>23或temp2作为数字>59,则-
temp:=temp1+temp2
如果temp与src相同,则-
newDiff:=eval(温度-eval(src))
如果newDiff<0,则-
如果newDiff<diff,则-
对于初始化j:=0,当j<n时,更新(将j增加1),执行-
返回(如果ret的大小等于0,则为t,否则为ret)
示例
让我们看下面的实现以更好地理解-
#include <bits/stdc++.h>
using namespace std;
class Solution {
public:
int eval(string x){
string a = to_string(x[0]);
a += x[1];
string b = to_string(x[2]);
b += x[3];
return stoi(a) * 60 + stoi(b);
}
string nextClosestTime(string t) {
string ret = "";
string temp = "";
int diff = INT_MAX;
vector<char> time;
time.push_back(t[0]);
time.push_back(t[1]);
time.push_back(t[3]);
time.push_back(t[4]);
int n = time.size();
string src = "";
string temp1 = "";
string temp2 = "";
for (int i = 0; i < n; i++)
src += time[i];
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
for (int k = 0; k < n; k++) {
for (int l = 0; l < n; l++) {
temp1 = time[i];
temp1 += time[j];
temp2 = time[k];
temp2 += time[l];
if (stoi(temp1) > 23 || stoi(temp2) > 59)
continue;
temp = temp1 + temp2;
if (temp == src)
continue;
int newDiff = eval(temp) - eval(src);
if (newDiff < 0)
newDiff += (60 * 24);
if (newDiff < diff) {
diff = newDiff;
ret = temp1 + ":" + temp2;
}
}
}
}
}
return ret.size() == 0 ? t : ret;
}
};
main(){
Solution ob;
cout<<(ob.nextClosestTime("19:34"));
}输入值
"19:34"
输出结果
19:39