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