流程/思路:
package controller;
import java.util.*;
import java.util.stream.Collectors;
public class TestController {
/**
* @param unusableTimeList 所有时间段:[startTime, endTime, startTime, endTime, startTime, endTime]
* @return 返回时间段:[startTime, endTime, startTime, endTime]
*/
public static List<Long> getOverlapTimeRange(List<Long> unusableTimeList) {
List<Long> finalUnusableTimeList = new ArrayList<>();
// 统计时间段,去重
Map<List<Long>, Integer> timeRangeMap = new HashMap<>();
// 获取每段时间的时间点,去重
Set<Long> timeSet = new HashSet<>(unusableTimeList);
// 将Set转换为List, 并排序
List<Long> newUnusableTimeList = new ArrayList<>(timeSet).stream().sorted(Long::compareTo).collect(Collectors.toList());
// 统计每段时间的重复次数
Map<String, Integer> timeRangeReserCountMap = new HashMap<>();
for (int i = 0; i < newUnusableTimeList.size(); i++) {
if (i + 1 == newUnusableTimeList.size()) break;
// 每段时间的间隔
Long startInt = newUnusableTimeList.get(i);
Long endInt = newUnusableTimeList.get(i + 1);
String key = startInt + "_" + endInt;
// 每段时间的重复次数
Integer timeRangeCount = timeRangeReserCountMap.get(key) != null ? timeRangeReserCountMap.get(key) : 0;
//迭代每段时间范围,算出每子时间段内的重复时间占用数量
for (int j = 0; j < unusableTimeList.size(); j = j + 2) {
if (j + 1 == unusableTimeList.size()) break;
//预约开始结束范围
Long reserStartInt = unusableTimeList.get(j);
Long reserEndInt = unusableTimeList.get(j + 1);
if (reserStartInt <= startInt && endInt <= reserEndInt) {
timeRangeCount++;
}
if (timeRangeReserCountMap.get(key) != null && timeRangeReserCountMap.get(key) > 1) { // 判断该时间段是否达到某种需求条件,这里为时间段重复次数大于1的就返回
timeRangeMap.put(Arrays.asList(startInt, endInt), timeRangeCount);
}
timeRangeReserCountMap.put(key, timeRangeCount);
}
}
for (Map.Entry<List<Long>, Integer> entry : timeRangeMap.entrySet()) {
finalUnusableTimeList.addAll(entry.getKey());
}
return finalUnusableTimeList;
}
public static void main(String[] args) {
List<Long> unusableTimeList = new ArrayList<>();
unusableTimeList.add(20200513000000L);
unusableTimeList.add(20200513235959L);
unusableTimeList.add(20200513120000L);
unusableTimeList.add(20200513235959L);
unusableTimeList.add(20200513101010L);
unusableTimeList.add(20200513111111L);
unusableTimeList.add(20200513131313L);
unusableTimeList.add(20200513151515L);
List<Long> overlapTimeRange = getOverlapTimeRange(unusableTimeList);
System.out.println(overlapTimeRange);
}
}