This question comes from an interview question: the leader held a meeting, listed several dates, and asked the dates to hold up to several meetings. I knew the general idea at the time, but I didn’t write it out at the first time. Then I thought about it and wrote it at night. This article is for reference only
For example:
[9:00,10:20]", "[10:10,10:50]", "[10:21,10:50]", "[11:20,12:30]
Core idea: Convert the time interval to a digital interval, because the time itself is converted to a millisecond value of long type
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();
}
}
convert to milliseconds
//[9:00,10:20]", "[10:10,10:50]", "[10:21,10:50]", "[11:20,12:30]
[[3600000, 8400000], [7800000, 10200000], [8460000, 10200000], [12000000, 16200000]]
So the problem becomes the problem of finding the largest continuous subinterval
find all series
[
[[3600000, 8400000], [8460000, 10200000]]
, [[3600000, 8400000], [8460000, 10200000], [12000000, 16200000]]
, [[3600000, 8400000], [12000000, 16200000]]
, [[7800000, 10200000], [12000000, 16200000]]
, [[8460000, 10200000], [12000000, 16200000]]
]
final result range
[[3600000, 8400000], [8460000, 10200000], [12000000, 16200000]]
//[9:00,10:20]", "[10:21,10:50]", "[11:20,12:30]