0
点赞
收藏
分享

微信扫一扫

贪心(Java)

田妞的读书笔记 2022-04-13 阅读 109
贪心

文章目录


package 贪心;

// https://leetcode-cn.com/problems/maximum-number-of-events-that-can-be-attended/
// 贪心
import java.util.Arrays;
import java.util.Comparator;
import java.util.PriorityQueue;

class _贪心进阶 {

    public int maxEvents(int[][] events) {

        //根据开始时间排序
        Arrays.sort(events, Comparator.comparingInt(o -> o[0]));

        int count = 0,startDay = 1,i=0;

        PriorityQueue<Integer> canJoin = new PriorityQueue<>(Comparator.comparingInt(o -> o));

        while (i<events.length||!canJoin.isEmpty()){

            while (!canJoin.isEmpty()&&canJoin.peek()<startDay){//可能有些已经超过参加时间了,处理一下
                canJoin.poll();
            }

            while (i<events.length&&events[i][0]<=startDay){//把当前能够参加的会议的结束时间都丢进canJoin中,
                canJoin.add(events[i++][1]);                //当前不能参加的表示startDay还没到,之后可能还有机会参加
            }

            if(!canJoin.isEmpty()){
                canJoin.poll();
                count++;
            }

            startDay++;
        }

        return count;
    }
}
举报

相关推荐

0 条评论