Skip to content

Conversation

@Kaichi-Irie
Copy link
Owner

問題へのリンク

Meeting Rooms - LeetCode

言語

Python

問題の概要

ある人が複数の会議に出席できるかを判定する問題である。

  • 各会議は時間帯 [starti, endi] で表される。
  • 入力は、こうした会議の時間帯のリスト intervals で与えられる。
  • すべての会議に出席するには、会議同士が重ならない必要がある。

例1:

入力: [[0,30],[5,10],[15,20]]
出力: false(0〜30と5〜10が重なるため)

例2:

入力: [[7,10],[2,4]]
出力: true(会議が重ならないため)

制約:

  • 会議数は 0〜10,000 件
  • 各会議の時間帯は [starti, endi](開始 < 終了、かつ0以上1,000,000以下)

自分の解法

intervals の時間帯を開始時間でソートし、隣接する会議の終了時間と開始時間を比較する方法。ひとつでも重なっている会議があれば、False を返す。

  • 時間計算量:O(nlogn)
  • 空間計算量:O(1)

step2

  • start, end の変数名を start_time, end_time に変更して、より明確にした。

別解・模範解答

intervals からすべての時間帯のペアを取り出し、そのペアが重なるかどうかを確認する方法。

  • 時間計算量:O(n^2)(すべてのペアを確認するため)
  • 空間計算量:O(1)

次に解く問題の予告

- `start`, `end` の変数名を `start_time`, `end_time` に変更して、より明確にした。

# 別解・模範解答
`intervals` からすべての時間帯のペアを取り出し、そのペアが重なるかどうかを確認する方法。
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

他に、(開始時間, 1)、(終了時間, -1) と書かれた紙を箱に入れて、小さい順に取り出して、開始と終了が交互に出てくるかどうかを確認するという方法もありそうですね。

Copy link
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

レビューありがとうございます。
確かにそうですね、早速実装してみました。

TIME_POINT_START = 1
TIME_POINT_END = -1


class Solution:
    def canAttendMeetings(self, intervals: list[list[int]]) -> bool:
        time_points: list[tuple[int, int]] = []
        for start_time, end_time in intervals:
            time_points.append((start_time, TIME_POINT_START))
            time_points.append((end_time, TIME_POINT_END))

        time_points.sort()
        # time_points must have start time and end time in alternating order after sorting
        # if not, then there are overlapping intervals
        previous_time_type = TIME_POINT_END
        for _, time_type in time_points:
            if time_type == previous_time_type:
                return False
            previous_time_type = time_type
        return True

start_time2: int,
end_time2: int,
) -> bool:
if start_time1 < end_time1 <= start_time2 < end_time2:
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

return max(start_time1, start_time2) < min(end_time1, end_time2)

と書けると思いました。ただ、ややパズルに感じられるため、元のコードのほうがよいかもしれません。

Copy link
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

レビューありがとうございます。
確かにそうですね。テクニックの一つとして、頭に留めておきます。

@Mike0121
Copy link

良いと思いました:)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

5 participants