[leetcode#252] Meeting Rooms

Source: Internet
Author: User

problem:

Given An array of meeting time intervals consisting of start and end Times [[s1,e1],[s2,e2],...] (Si < EI), determine if a person could Attend all meetings.

For example,
Given [[0, 30],[5, 10],[15, 20]] ,
Return false .

Analysis:

The problem is very easy!!!But I had made a mistake in defining Comparator.comparator<Interval> Interval_sort =NewComparator<interval>() {@Override Public intCompare (Interval interval_1, Interval interval_2) {if(Interval_1.start <Interval_2.start)returnInterval_1.start-Interval_2.start; returnInterval_1.end-Interval_2.end; }}; Error Case: Runtime Error message:line53:java.lang.illegalargumentexception:comparison method violates its general contract!This is a logic error forThe above code.suppose we have Interval_1 and interval_2. IFF Interval_1.start< Interval_2.start, we wouldreturnreturnInterval_1.start-interval_2.start; <a Negative number>The error is at otherwise. whatifWe swap the reference of them, can we still get the same answer?Iff"Interval_1.start > Interval_2.start"?Then we use the end forTHE comparision!!!! Why don ' t just use start!!!! Wrong! right!If You indeed want take the end into consideration. Should use"= =", which would not BreakThe comparision ' s logic.if(Interval_1.start = =Interval_2.start)return returnInterval_1.end-Interval_2.end;returnInterval_1.start-interval_2.start;

Solution:

 Public classSolution { Public Booleancanattendmeetings (interval[] intervals) {if(Intervals = =NULL)            Throw NewIllegalArgumentException ("Intervals is null"); intLen =intervals.length; if(Len <= 1)            return true; Comparator<Interval> Interval_sort =NewComparator<interval>() {@Override Public intCompare (Interval interval_1, Interval interval_2) {returnInterval_1.start-Interval_2.start;        }        };        Arrays.sort (intervals, interval_sort);  for(inti = 1; i < Len; i++) {            if(Intervals[i-1].end >Intervals[i].start)return false; }        return true; }}

[leetcode#252] Meeting Rooms

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.