C++程序:查找两对时钟读数之间可能的最大最小时间差
假设我们有一个包含N个元素的数组D。考虑在一个代码节上,包括Amal在内有N+1个参与者。Amal检查并发现他所在城市和第i个人的城市之间的当地时间差为D[i]小时。两个城市之间的时间差:对于任意两个城市A和B,如果在城市A的当地时间为0点时,城市B的当地时间为d点,那么这两个城市之间的时间差为d和24-d小时中的较小者。
这里,我们使用24小时制。然后,对于从N+1个人中选择的任意两个人,他写下了他们城市之间的时间差。设其中最小的时差为s小时。我们需要找到s的最大可能值。
因此,如果输入类似于D = [7, 12, 8],则输出为4,因为第二人和第三个人城市之间的时间差为4小时。
步骤
为了解决这个问题,我们将遵循以下步骤:
n := size of D
sort the array D
Define an array t
insert 0 at the end of t
for initialize i := 0, when i < n, update (increase i by 1), do:
if i mod 2 is same as 0, then:
insert D[i] at the end of t
Otherwise
insert 24 - D[i] at the end of t
sort the array t
ans := inf
for initialize i := 1, when i < size of t, update (increase i by 1), do:
ans := minimum of ans and t[i] - t[i - 1]
return ans示例
让我们看看下面的实现来更好地理解:
#include <bits/stdc++.h>
using namespace std;
int solve(vector<int> D) {
int n = D.size();
sort(D.begin(), D.end());
vector<int> t;
t.push_back(0);
for (int i = 0; i < n; i++){
if (i % 2 == 0)
t.push_back(D[i]);
else
t.push_back(24 - D[i]);
}
sort(t.begin(), t.end());
int ans = 1e9;
for (int i = 1; i < t.size(); i++){
ans = min(ans, t[i] - t[i - 1]);
}
return ans;
}
int main(){
vector<int> D = { 7, 12, 8 };
cout << solve(D) << endl;
}输入
{ 7, 12, 8 }
输出
4
广告
数据结构
网络
关系数据库管理系统 (RDBMS)
操作系统
Java
iOS
HTML
CSS
Android
Python
C语言编程
C++
C#
MongoDB
MySQL
Javascript
PHP