运维工程师采集到某产品线网运行一天产生的日志n条,现需根据日志时间先后顺序对日志进行排序,日志时间格式为H:M:S.N。
H表示小时(0~23)
M表示分钟(0~59)
S表示秒(0~59)
N表示毫秒(0~999)
时间可能并没有补全,也就是说,01:01:01.001也可能表示为1:1:1.1。
输入描述:
第一行输入一个整数n表示日志条数,1<=n<=100000,接下来n行输入n个时间。
输出描述:
按时间升序排序之后的时间,如果有两个时间表示的时间相同,则保持输入顺序。
示例:
输入:
2
01:41:8.9
1:1:09.211
输出:
1:1:09.211
01:41:8.9
输入:
3
23:41:08.023
1:1:09.211
08:01:22.0
输出:
1:1:09.211
08:01:22.0
23:41:08.023
输入:
2
22:41:08.023
22:41:08.23
输出:
22:41:08.023
22:41:08.23
#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
using namespace std;
//转millsecond比较
int getMsecondTime(string time) {
vector<string>temp;
//先按":"分割
while (time.find(":") != string::npos)
{
int found = time.find(":");
temp.push_back(time.substr(0, found));
time = time.substr(found + 1);
}
temp.push_back(time); //处理最后一段时间
int hour = stoi(temp[0]) * 60 * 1000 * 1000;
int minute = stoi(temp[1]) * 60 * 1000;
int found = time.find("."); //分割第三个字段的"."
int second = stoi(temp[2].substr(0, found)) * 1000;
int millSec = stoi(temp[2].substr(found + 1));
return hour +minute + second + millSec;
}
bool cmp(pair<int, string> a, pair<int, string> b) {
if (a.first < b.first)
{
return true;
}
return false;
}
int main() {
string strCnt;
getline(cin, strCnt);
int n = stoi(strCnt);
vector<string> strTime;
for (int i = 0; i < n; i++)
{
string time;
getline(cin, time);
strTime.push_back(time);
}
vector<pair<int, string>> mSecTime;
for (string& str : strTime)
{
mSecTime.push_back(make_pair(getMsecondTime(str), str));
}
sort(mSecTime.begin(), mSecTime.end(), cmp);
for (auto& e : mSecTime)
{
cout << e.second << endl;
}
return 0;
}