Eat Study Love

먹고 공부하고 사랑하라

Coding_Practice

My Calendar II[Array,Binary Search,Design,Segment Tree,Prefix Sum,Ordered Set]

eatplaylove 2024. 10. 24. 22:44

https://leetcode.com/problems/my-calendar-ii/description/

You are implementing a program to use as your calendar. We can add a new event if adding the event will not cause a triple booking.

A triple booking happens when three events have some non-empty intersection (i.e., some moment is common to all the three events.).

The event can be represented as a pair of integers start and end that represents a booking on the half-open interval [start, end), the range of real numbers x such that start <= x < end.

Implement the MyCalendarTwo class:

  • MyCalendarTwo() Initializes the calendar object.
  • boolean book(int start, int end) Returns true if the event can be added to the calendar successfully without causing a triple booking. Otherwise, return false and do not add the event to the calendar.

 

Example 1:

Input
["MyCalendarTwo", "book", "book", "book", "book", "book", "book"]
[[], [10, 20], [50, 60], [10, 40], [5, 15], [5, 10], [25, 55]]
Output
[null, true, true, true, false, true, true]

Explanation
MyCalendarTwo myCalendarTwo = new MyCalendarTwo();
myCalendarTwo.book(10, 20); // return True, The event can be booked. 
myCalendarTwo.book(50, 60); // return True, The event can be booked. 
myCalendarTwo.book(10, 40); // return True, The event can be double booked. 
myCalendarTwo.book(5, 15);  // return False, The event cannot be booked, because it would result in a triple booking.
myCalendarTwo.book(5, 10); // return True, The event can be booked, as it does not use time 10 which is already double booked.
myCalendarTwo.book(25, 55); // return True, The event can be booked, as the time in [25, 40) will be double booked with the third event, the time [40, 50) will be single booked, and the time [50, 55) will be double booked with the second event.

 

Constraints:

  • 0 <= start < end <= 109
  • At most 1000 calls will be made to book.

예전에 비스무리한 문제 풀어 본 적이 있는 거 같은데,,

 

뭔가 Binary Search느낌이 쌔하게 나는게 문제 자체가 쉽진 않아보인당 -_-

 

1. Python

어렵다!!!!!!!!

class MyCalendarTwo:

    def __init__(self):
        self.s1 = set()        
        self.s2 = set()        
    def book(self, start: int, end: int) -> bool:
        for x in range(start,end):
            if x in self.s2 : return False
        for x in range(start,end):
            if x not in self.s1:
                self.s1.add(x)
            else:
                self.s2.add(x)
        return True


# Your MyCalendarTwo object will be instantiated and called as such:
# obj = MyCalendarTwo()
# param_1 = obj.book(start,end)

 

아오 거지 같은거

Naive하게 풀면, 꼭 memory 핵 빡센 예제에 걸린다

for문 2개 돌리는 건 좀 양심 찔리긴 한데;; 봐주라 이놈아!!

 

class MyCalendarTwo:

    def __init__(self):
        self.s1 = set()        
        self.s2 = set()        
    def book(self, start: int, end: int) -> bool:
        for s,e in self.s2 :
            if start < e and end > s : return False
        
        for s,e in self.s1:
            if start < e and end > s :
                self.s2.add((max(start,s),min(end,e)))
        
        self.s1.add((start,end))
        return True

# Your MyCalendarTwo object will be instantiated and called as such:
# obj = MyCalendarTwo()
# param_1 = obj.book(start,end)

 

희한한게 이것도 for문 2개 돌리는 건 똑같은데, 얘네는 memory / time limit에 걸리지 않는다.

Data를 range하게 놓고 for문을 돌려서 그런가보다.

 

2. C

C는 역시 오바다.

 

뭐가 많다..

#include <stdio.h>
#include <stdlib.h>

typedef struct {
    int start;
    int end;
} Interval;

typedef struct {
    Interval* calendar; // 모든 예약을 저장할 배열
    Interval* overlaps; // 이중 예약을 저장할 배열
    int calendar_size;
    int overlaps_size;
    int calendar_capacity;
    int overlaps_capacity;
} MyCalendarTwo;

// MyCalendarTwo 객체 초기화 함수
MyCalendarTwo* myCalendarTwoCreate() {
    MyCalendarTwo* obj = (MyCalendarTwo*)malloc(sizeof(MyCalendarTwo));
    obj->calendar = (Interval*)malloc(10 * sizeof(Interval));
    obj->overlaps = (Interval*)malloc(10 * sizeof(Interval));
    obj->calendar_size = 0;
    obj->overlaps_size = 0;
    obj->calendar_capacity = 10;
    obj->overlaps_capacity = 10;
    return obj;
}

// 동적 배열 크기 조정 함수
void resizeIfNeeded(Interval** array, int* capacity, int size) {
    if (size >= *capacity) {
        *capacity *= 2;
        *array = (Interval*)realloc(*array, *capacity * sizeof(Interval));
    }
}

// 예약을 추가하는 함수
int myCalendarTwoBook(MyCalendarTwo* obj, int start, int end) {
    // 이중 예약이 세 번 이상 발생하는지 확인
    for (int i = 0; i < obj->overlaps_size; i++) {
        if (start < obj->overlaps[i].end && end > obj->overlaps[i].start) {
            return 0; // 세 번 이상 겹치면 False
        }
    }

    // 기존 예약과 겹치는 부분을 찾아서 overlaps에 추가
    for (int i = 0; i < obj->calendar_size; i++) {
        if (start < obj->calendar[i].end && end > obj->calendar[i].start) {
            int overlap_start = start > obj->calendar[i].start ? start : obj->calendar[i].start;
            int overlap_end = end < obj->calendar[i].end ? end : obj->calendar[i].end;
            resizeIfNeeded(&obj->overlaps, &obj->overlaps_capacity, obj->overlaps_size);
            obj->overlaps[obj->overlaps_size++] = (Interval){overlap_start, overlap_end};
        }
    }

    // 새 예약을 calendar에 추가
    resizeIfNeeded(&obj->calendar, &obj->calendar_capacity, obj->calendar_size);
    obj->calendar[obj->calendar_size++] = (Interval){start, end};
    return 1; // 성공적으로 예약 완료
}

// 메모리 해제 함수
void myCalendarTwoFree(MyCalendarTwo* obj) {
    free(obj->calendar);
    free(obj->overlaps);
    free(obj);
}

int main() {
    MyCalendarTwo* calendar = myCalendarTwoCreate();
    
    // 예시 입력에 대한 테스트
    printf("%d\n", myCalendarTwoBook(calendar, 26, 35)); // true
    printf("%d\n", myCalendarTwoBook(calendar, 26, 32)); // true
    printf("%d\n", myCalendarTwoBook(calendar, 25, 32)); // false
    printf("%d\n", myCalendarTwoBook(calendar, 18, 26)); // true
    printf("%d\n", myCalendarTwoBook(calendar, 40, 45)); // true
    printf("%d\n", myCalendarTwoBook(calendar, 19, 26)); // false
    printf("%d\n", myCalendarTwoBook(calendar, 48, 50)); // true
    printf("%d\n", myCalendarTwoBook(calendar, 1, 6));   // true
    printf("%d\n", myCalendarTwoBook(calendar, 46, 50)); // true
    printf("%d\n", myCalendarTwoBook(calendar, 11, 18)); // true
    
    // 메모리 해제
    myCalendarTwoFree(calendar);
    
    return 0;
}

 

3. C++

그나마 C++은 비빌 수 있겠지요

#include <vector>
using namespace std;

class MyCalendarTwo {
public:
        vector<vector<int>> vec1;
        vector<vector<int>> vec2;
    MyCalendarTwo() {}
    
    bool book(int start, int end) {
        for(auto vec : vec2){
            if(start < vec[1] && end > vec[0]) return false;
        }
        for(auto vec : vec1){
            if(start < vec[1] && end > vec[0]){
                vec2.push_back({max(start,vec[0]),min(end,vec[1])});}
            }
        vec1.push_back({start,end});
        return true;
    }
};

/**
 * Your MyCalendarTwo object will be instantiated and called as such:
 * MyCalendarTwo* obj = new MyCalendarTwo();
 * bool param_1 = obj->book(start,end);
 */

 

거의 python과 같은 알고리즘으로 풀었다.

근데 그냥 vector<pair<int,int>> 할 걸 그랬다. 얘가 가독성이 더 좋