贪心算法的区间调度问题,返回可以执行的任务号

本文介绍了一种基于任务结束时间升序排列的任务调度算法,通过优化任务执行顺序,提高资源利用率和任务完成效率。该算法首先将所有任务按其结束时间进行排序,然后选择最早结束时间的任务执行,以此类推,直至所有任务完成。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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);
    }
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值