华为机试真题 C++ 实现【运维日志排序】

运维工程师采集到某产品线网运行一天产生的日志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;
}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值