본문 바로가기

코딩테스트/LeetCode

[LeetCode] My Calendar I

문제링크

 

My Calendar I - LeetCode

Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview.

leetcode.com

 

생성자를 통해 인스턴스 객체(달력)을 만들고
예약 메서드(book)으로 스케줄 일정을 받아서
새로운 스케줄이 기존 스케줄과 겹치면 false, 겹치지 않으면 true를 반환하는 문제이다.

접근 방법

문제는 prototype으로 풀이가 주어졌는데 class로 한번 접근해 보았다.


생성자를 만들고 스케줄을 담을 배열을 만든다.
constructor(){
    this.times = [];
}​

 

이는 생성자 함수의 부분과 같은 역할을 한다.


그리고 예약 메서드 book을 생성하고 새로 입력받을 스케줄이 기존 스케줄과 겹치지 않는지 체크하는 조건을 추가한다.
book(start, end){
    for(let time of this.times){
        if(time[1] > start && time[0] < end){
            return false;
        }
    }

    this.times.push([start, end])
    return true; 
}​

이는 생성자 함수의 prototype에 추가할 메서드 부분과 같은 역할을 한다.

모든 스케줄(times)를 순회하며 만약 겹치는 부분이 있으면 false를 반환하고
for문을 안전하게 통과하면 새로운 스케줄을 push하고 true를 반환한다. 

 

/** 
 * Your MyCalendar object will be instantiated and called as such:
 * var obj = new MyCalendar()
 * var param_1 = obj.book(start,end)
 */

 class MyCalendar {
    
    constructor(){
        this.times = [];
    }

    book(start, end){
        
        for(let time of this.times){
            if(time[1] > start && time[0] < end){
                return false;
            }
        }
            
        this.times.push([start, end])
        return true; 
    }
}