【貪心】B036_LC_最多可以參加的會議數目(排序 / pq)

一、Problem

Given an array of events where events[i] = [startDayi, endDayi]. Every event i starts at startDayi and ends at endDayi.

You can attend an event i at any day d where startTimei <= d <= endTimei. Notice that you can only attend one event at any time d.

Return the maximum number of events you can attend.

在這裏插入圖片描述

Input: events = [[1,2],[2,3],[3,4]]
Output: 3
Explanation: You can attend all the three events.
One way to attend them all is as shown.
Attend the first event on day 1.
Attend the second event on day 2.
Attend the third event on day 3.

二、Solution

方法一:排序(超時)

思路

  • 會議時間參差不齊,我們更希望看到是整齊的,那我們有兩種選擇:
    • 按照開始時間 s 升序排列
    • 按照結束時間 e 升序排列
    • 按照會議持續時間 e-s 升序排列
  • 這兩點我不清楚,但是我很明確參加結束時間越早的會議,我有更多的選擇取參加其他會議,基於這點,我選擇按第二點排序。

算法

  • 排序…
  • 如果參加了某一個正在進行會議,那麼我們是無法在此期間參加其他會議的。
  • 所以我們需要記錄某一個會議的持續時間狀態。
  • 選擇參加一個會議後,就立馬枚舉下一個會議了。

總之一句話:在所有時間裏面找空隙,但很不幸超時了,對於 [[1,1],[1,2],[1,3],[1,4],[1,n]][[1,1],[1,2],[1,3],[1,4], [1,n]] 這種事要遍歷 n2n^2 次。

class Solution {
    public int maxEvents(int[][] es) {
        Arrays.sort(es, (e1, e2) -> e1[1] - e2[1]);
        Set<Integer> now = new HashSet<>();
        for (int[] e : es)
        for (int i = e[0]; i <= e[1]; i++) {
            if (!now.contains(i)) {
                now.add(i);
                break;
            }
        } 
        return now.size();
    }
}

複雜度分析

  • 時間複雜度:O(n2)O(n^2)
  • 空間複雜度:O(n)O(n)

方法二:pq

思想大題相同,用一個自變量 day 來記錄天數,符合天數會議將結束時間的入隊,過期的會議出隊。

class Solution {
    public int maxEvents(int[][] es) {
        Arrays.sort(es, (e1, e2) -> e1[0] - e2[0]);
        Queue<Integer> q = new PriorityQueue<>();
        int i = 0, day = 1, n = es.length, cnt = 0;
        while (i < n || !q.isEmpty()) {
            while (i < n && es[i][0] == day)
                q.add(es[i++][1]);
            while (!q.isEmpty() && q.peek() < day)
                q.poll();
            if (!q.isEmpty()) {
                q.poll();
                cnt++;
            }
            day++;
        }
        return cnt;
    }
}

複雜度分析

  • 時間複雜度:O(nlogn)O(nlogn)
  • 空間複雜度:O(n)O(n)
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章