1.对 map 集合的 value 数组的第二列(任务的结束时间)做升序操作
2.每次都选取结束时间最早的工作,主要是用map记录了一下可以执行的任务号
import java.util.*;
import java.util.stream.Collectors;
public class demo05 {
public static List solve(Map<Integer,int[]> map){
List<Integer> task_num = new ArrayList<>();
int t = 0,ans = 0;
for (Map.Entry<Integer,int[]> entry: map.entrySet()) {
if (t<entry.getValue()[0]){
ans++;
task_num.add(entry.getKey());
t = entry.getValue()[1];
}
}
System.out.println(ans);
return task_num;
}
public static void main(String[] args) {
// 起始时间 结束时间
int[][] a = {{1,3},{6,9},{4,7},{8,10},{2,5}};
// 记录每个任务的任务号
Map<Integer,int[]> map = new HashMap<>();
int i = 0;
for (int[] s: a) {
map.put(i++,s);
}
// 按任务的结束时间做升序操作,即 value 数组种的第二列升序
Map<Integer, int[]> collect = map.entrySet().stream()
.sorted(Map.Entry.comparingByValue(Comparator.comparingInt(o -> o[1])))
.collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue,
(oldValue,newValue)->oldValue,LinkedHashMap::new));
for (Map.Entry<Integer,int[]> entry: collect.entrySet()) {
System.out.println(entry.getKey()+" "+entry.getValue()[0]+" " +entry.getValue()[1]);
}
List solve = solve(collect);
System.out.println(solve);
}
}