此问题出自一道面试题:领导开会,列举了几个日期,问日期最多可以开几场会议,当时知道大体思路,但没第一时间写出来,然后晚上想了一下写写,本文仅供参考
例如:
[9:00,10:20]", "[10:10,10:50]", "[10:21,10:50]", "[11:20,12:30]
核心思路:将时间区间转为数字区间,因为时间本身转为long类型的毫秒值
private static LinkedList<LinkedList<List<Long>>> result = new LinkedList<>();
public static void main(String[] args) throws Exception {
List<String> list = Arrays.asList("[9:00,10:20]", "[10:10,10:50]", "[10:21,10:50]", "[11:20,12:30]");
LinkedList<List<Long>> nums = new LinkedList<>();
for (String s : list) {
String replace1 = s.replace("[", "").replace("]", "");
String[] split = replace1.split(",");
SimpleDateFormat format = new SimpleDateFormat("HH:mm");
Date parse = format.parse(split[0]);
Date parse2 = format.parse(split[1]);
List<Long> longs = new ArrayList<>();
longs.add(parse.getTime());
longs.add(parse2.getTime());
nums.add(longs);
}
System.out.println(nums);
backTrack(nums, new LinkedList<List<Long>>(), 0);
System.out.println(result);
for (LinkedList<List<Long>> lists : result) {
System.out.println(lists.size());
}
}
public static void backTrack(LinkedList<List<Long>> nums,LinkedList<List<Long>> tmp,int num){
if (tmp != null && tmp.size() > 1) {
List<Long> longs = tmp.get(tmp.size()-2);
List<Long> longs2 = tmp.get(tmp.size()-1);
Long aLong = longs.get(1);
Long aLong1 = longs2.get(0);
if (aLong1 < aLong) {
return;
}else {
result.add(new LinkedList<>(tmp));
}
}
for (int i = num; i <nums.size() ; i++) {
tmp.add(nums.get(i));
backTrack(nums, tmp, i + 1);
tmp.removeLast();
}
}
转为毫秒值
//[9:00,10:20]", "[10:10,10:50]", "[10:21,10:50]", "[11:20,12:30]
[[3600000, 8400000], [7800000, 10200000], [8460000, 10200000], [12000000, 16200000]]
这样问题便成了求最大连续子区间问题
求出所有系列
[
[[3600000, 8400000], [8460000, 10200000]]
, [[3600000, 8400000], [8460000, 10200000], [12000000, 16200000]]
, [[3600000, 8400000], [12000000, 16200000]]
, [[7800000, 10200000], [12000000, 16200000]]
, [[8460000, 10200000], [12000000, 16200000]]
]
最终结果区间
[[3600000, 8400000], [8460000, 10200000], [12000000, 16200000]]
//[9:00,10:20]", "[10:21,10:50]", "[11:20,12:30]