我有一个长字符串,表示进程的开始和结束时间。 我需要在这里找到最常见的时间(进程最多的分钟)。 字符串看起来像这样:“第一个 15:15 12:10 第二个 12:50 17:10 第三个 20:23 22:20 ...” 以及更多进程。 怎么做?
最佳答案
好吧,我不得不承认,即使是显而易见的解决方案,当用 Java 编写时,看起来也相当复杂,主要是由于:
- 缺少配对
- 缺少
findAllIn
-正则表达式方法 - 缺少
scanLeft
上Stream
但是,这是:
String data = "first 15:15 17:10 second 12:50 17:10 third 20:23 22:20 fourth 14:30 16:49";
Pattern regex = Pattern.compile("(?:\\d{2}:\\d{2} ?){2}");
LinkedList<String> matches = new LinkedList<>();
Matcher matcher = regex.matcher(data);
while (matcher.find()) {
matches.add(matcher.group(0));
}
final int[] acc_max = new int[2];
matches
.stream()
.flatMap(s -> {
String[] pieces = s.trim().split(" ");
return Stream.of(pieces[0] + " +", pieces[1] + " -");
})
.sorted()
.map(s -> s.charAt(s.length() - 1))
.forEachOrdered(c -> {
if (c == '+') {
acc_max[0]++;
} else {
acc_max[0]--;
}
if (acc_max[0] > acc_max[1]) {
acc_max[1] = acc_max[0];
}
});
System.out.println("Maximum number of simultaneous processes: " + acc_max[1]);
简要说明:
- 正则表达式:无聊,你应该在发布问题之前就这样做
- 每对时间都平坦映射到
start +
,end -
,与+
和-
已附加 - 然后一切都已排序
- 然后删除时间,这样只剩下
+
和-
留下来 - 与
forEachOrdered
集成,将当前进程数保留在acc
中以及迄今为止在max
中看到的最大进程数. - 输出
max
最后。
打印:
Maximum number of simultaneous processes: 3
本质上,相同的算法还会为您提供达到最大并发进程数的分钟,但为此,您可能应该将时间间隔建模为适当的类,而不是粘合时间和 +-
-将字符转换为字符串。
关于java - 找出几个进程中最常见的时间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49174077/