|
| 1 | +package leetcode; |
| 2 | + |
| 3 | +import org.assertj.core.api.Assertions; |
| 4 | +import org.junit.jupiter.api.DisplayName; |
| 5 | +import org.junit.jupiter.api.Test; |
| 6 | + |
| 7 | +import java.util.ArrayList; |
| 8 | +import java.util.Comparator; |
| 9 | +import java.util.List; |
| 10 | + |
| 11 | +public class MeetingRooms { |
| 12 | + |
| 13 | + public class Interval { |
| 14 | + public int start, end; |
| 15 | + public Interval(int start, int end) { |
| 16 | + this.start = start; |
| 17 | + this.end = end; |
| 18 | + } |
| 19 | + } |
| 20 | + |
| 21 | + public boolean canAttendMeetings(List<Interval> intervals) { |
| 22 | + return usingBruteForce(intervals); |
| 23 | + } |
| 24 | + |
| 25 | + /** |
| 26 | + * TC: O(n^2), SC: O(1) |
| 27 | + */ |
| 28 | + private boolean usingBruteForce(List<Interval> intervals) { |
| 29 | + final int size = intervals.size(); |
| 30 | + for (int i = 0; i < size; i++) { |
| 31 | + Interval A = intervals.get(i); |
| 32 | + for (int j = i + 1; j < size; j++) { |
| 33 | + Interval B = intervals.get(j); |
| 34 | + if (Math.min(A.end, B.end) > Math.max(A.start, B.start)) { |
| 35 | + return false; |
| 36 | + } |
| 37 | + } |
| 38 | + } |
| 39 | + return true; |
| 40 | + } |
| 41 | + |
| 42 | + /** |
| 43 | + * TC: O(n log n), SC: O(1) |
| 44 | + */ |
| 45 | + private boolean usingSort(List<Interval> intervals) { |
| 46 | + intervals.sort(Comparator.comparingInt(i -> i.start)); |
| 47 | + |
| 48 | + for (int i = 1; i < intervals.size(); i++) { |
| 49 | + Interval first = intervals.get(i - 1); |
| 50 | + Interval second = intervals.get(i); |
| 51 | + |
| 52 | + if (first.end > second.start) { |
| 53 | + return false; |
| 54 | + } |
| 55 | + } |
| 56 | + |
| 57 | + return true; |
| 58 | + } |
| 59 | + |
| 60 | + @Test |
| 61 | + @DisplayName("입력받은 간격들의 충돌 여부를 반환한다.") |
| 62 | + void name() { |
| 63 | + Assertions.assertThat(canAttendMeetings(new ArrayList<>() {{ |
| 64 | + add(new Interval(0,30)); |
| 65 | + add(new Interval(5,10)); |
| 66 | + add(new Interval(15,20)); |
| 67 | + }} |
| 68 | + )).isFalse(); |
| 69 | + |
| 70 | + Assertions.assertThat(canAttendMeetings(new ArrayList<>() {{ |
| 71 | + add(new Interval(5, 8)); |
| 72 | + add(new Interval(9, 10)); |
| 73 | + }} |
| 74 | + )).isTrue(); |
| 75 | + } |
| 76 | +} |
0 commit comments