LeetCode | 729. My Calendar I

来源:互联网 发布:虎鲨软件站 编辑:程序博客网 时间:2024/04/30 06:27

Implement a MyCalendar classto store your events. A new event can be added if adding the event will notcause a double booking.

Your class will have the method, book(intstart, int end).Formally, this represents a booking on the half open interval [start, end), therange of real numbers x suchthat start <= x < end.

A doublebooking happens when two events havesome non-empty intersection (ie., there is some time that is common to bothevents.)

For each call to the method MyCalendar.book,return true if theevent can be added to the calendar successfully without causing a doublebooking. Otherwise, return false and donot add the event to the calendar.

Your class will be called like this: MyCalendarcal = new MyCalendar(); MyCalendar.book(start,end)

Example 1:

MyCalendar();

MyCalendar.book(10, 20); // returns true

MyCalendar.book(15, 25); // returns false

MyCalendar.book(20, 30); // returns true

Explanation:

The first event can be booked.  The second can't because time 15 is alreadybooked by another event.

The third event can be booked, as the first event takes everytime less than 20, but not including 20.

Note:

· The number of calls to MyCalendar.book pertest case will be at most 1000.

· In calls to MyCalendar.book(start, end)start and end areintegers in the range [0, 10^9].

简单题,题目的意思是不断的给你一个范围,问你可不可以把这个范围插入类中,当这个范围和其他范围交叉的时候可以插入,但是一旦这个范围和其他范围交叉的时候,就不能吧这个范围插入类的数组中,就把这题当做锻炼思维吧

class MyCalendar {

public:

 

      MyCalendar(){

 

      }

      vector<pair<int, int>> theBooks;

      boolbook(int start, int end) {

 

            boolcan = true; int i;

            for(i = 0; i<theBooks.size(); i++)

                  if(start>=theBooks[i].first)

                  {

                       if(start >= theBooks[i].second) continue;

                       else

                       {

                             can= false; break;

                       }

                  }

                  else

                  {

                       if(end <= theBooks[i].first) { theBooks.insert(theBooks.begin() + i,pair<int, int>(start, end)); break; }

                       else

                       {

                             can= false; break;

                       }

                  }

            if(i== theBooks.size()) theBooks.push_back(pair<int,int> (start, end));

            returncan;

      }

};

原创粉丝点击