华为OD机试-运维日志排序
一种写法是,使用 TreeSet 和比较器进行排序,需要注意的是 Set本身是自带去重的,在定义比较器时,需要排除相等的情况。另一种写法,是使用集合类本身的 sort 方法,以及比较器进行排序,因为这里使用的是 list ,不会去重,因此不做特殊处理。运维工程师采集到某产品线网运行一天产生的日志n条,现需根据日志时间先后顺序对日志进行排序,日志时间格式为H:M:S.N。
·
题目描述
运维工程师采集到某产品线网运行一天产生的日志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
Java 代码实现
按照日志内容,分析并定义对应的日志内容类 LogBody
。
按照题目要求,对日志时间排序,这里写了两种写法,略有差异。
一种写法是,使用 TreeSet 和比较器进行排序,需要注意的是 Set本身是自带去重的,在定义比较器时,需要排除相等的情况。
另一种写法,是使用集合类本身的 sort 方法,以及比较器进行排序,因为这里使用的是 list ,不会去重,因此不做特殊处理。
package com.example;
import lombok.Data;
import java.util.*;
/**
* 华为OD机试-运维日志排序
*
* @version v1.0
* @author: fengjinsong
* @date: 2023年02月25日 14时58分
*/
public class LogSortDemo {
static Scanner input = new Scanner(System.in);
public static void main(String[] args) {
// 使用比较器将日志体安装时间排序,针对于set而言,没有相等的情况(会自动去重)
Comparator<LogBody> comparatorByLogTimeForSet = (o1, o2) ->
(o1.millSeconds + o1.seconds * 1000 + o1.minutes * 60 * 1000 + o1.hours * 60 * 60 * 1000)
- (o2.millSeconds + o2.seconds * 1000 + o2.minutes * 60 * 1000 + o2.hours * 60 * 60 * 1000) >= 0 ? 1 : -1;
// 使用比较器将日志体安装时间排序,针对于list而言,有相等的情况,但是不会自动去重
Comparator<LogBody> comparatorByLogTimeForList = Comparator.comparingInt(o -> (o.millSeconds + o.seconds * 1000 + o.minutes * 60 * 1000 + o.hours * 60 * 60 * 1000));
TreeSet<LogBody> treeSet = new TreeSet<>(comparatorByLogTimeForSet);
List<LogBody> logBodyList = new ArrayList<>();
System.out.println("输入日志条数:");
// 日志条数
for (int logCount = input.nextInt(); logCount > 0; logCount--) {
System.out.println("输入日志:");
String log = input.next();
// 将日志按照 小时:分钟:秒.毫秒 的格式进行切分
String[] logSplit = log.split(":");
LogBody logBody = new LogBody(logSplit[0], logSplit[1], logSplit[2], log);
treeSet.add(logBody);
logBodyList.add(logBody);
}
System.out.println("set排序");
treeSet.forEach(log -> System.out.println(log.sourceLog));
System.out.println("list排序");
logBodyList.sort(comparatorByLogTimeForList);
logBodyList.forEach(log -> System.out.println(log.sourceLog));
}
@Data
private static class LogBody {
public LogBody(String hours, String minutes, String secondsAndMillSeconds, String sourceLog) {
this.hours = Integer.parseInt(hours);
this.minutes = Integer.parseInt(minutes);
String[] secondsBody = secondsAndMillSeconds.split("\\.");
this.seconds = Integer.parseInt(secondsBody[0]);
this.millSeconds = Integer.parseInt(secondsBody[1]);
this.sourceLog = sourceLog;
}
private int hours;
private int minutes;
private int seconds;
private int millSeconds;
private String sourceLog;
}
}
更多推荐
所有评论(0)