运维工程师采集到某产品线网运行一天产生的日志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 <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <math.h>
#include <ctype.h>
typedef struct {
char str[100];
int H;
int M;
int S;
int N;
long long totalTime;
}LogTimeInfo;
int cmp(const void *a, const void *b){
LogTimeInfo * x = (LogTimeInfo *)a;
LogTimeInfo * y = (LogTimeInfo *)b;
if( x->totalTime > y->totalTime){
return 1;
} else if(x->totalTime < y->totalTime){
return -1;
}
//return x->totalTime - y->totalTime;
}
int main()
{
int num;
scanf("%d",&num);
LogTimeInfo *logList = malloc(sizeof(LogTimeInfo) * num);
for (int i = 0; i < num; i++) {
char *p = NULL;
char *q = NULL;
char s[100] = {0};
char tmpStr[4][10];
memset(tmpStr, 0, sizeof(tmpStr));
scanf("%s", s);
strcpy(logList[i].str, s);
int j = 0;
p = strtok(s, ":");
while (p != NULL) {
strcpy(tmpStr[j++], p);
p = strtok(NULL, ":");
}
logList[i].H = atoi(tmpStr[0]);
logList[i].M = atoi(tmpStr[1]);
//printf("tmpStr[2]:%s\n",tmpStr[2]);
int SNList[2] = {0};
int idx = 0;
q = strtok(tmpStr[2], ".");
while (q != NULL) {
SNList[idx++] = atoi(q);
q = strtok(NULL, ".");
}
logList[i].S = SNList[0];
logList[i].N = SNList[1];
logList[i].totalTime = logList[i].H *60*60*1000 + logList[i].M * 60 *1000 + logList[i].S *1000 + logList[i].N;
}
qsort(logList, num, sizeof(LogTimeInfo), cmp);
for (int i = 0; i < num; i++) {
//printf("%d %d %d %d %lld\n", logList[i].H, logList[i].M, logList[i].S, logList[i].N, logList[i].totalTime);
printf("%s\n", logList[i].str);
}
free(logList);
return 0;
}
该博客介绍了如何对日志按照时间顺序进行排序,日志时间格式为H:M:S.N,考虑了时间未补全的情况。博客提供了一种解决方案,并给出了多个输入输出示例。
490





