C#: Easy Intuitive Solution with Explanation. (Accepted)


  • 0

    0_1521518388838_a5a0cd39-42b7-493f-93cb-89e02735ebad-image.png
    Basic Idea: Sort the intervals based on their start-time, so that intervals are in the incresing order of the start-time, then you just need to check if the adjacent intervals are overlapping.

    public class Interval {
        public int start;
        public int end;
        public Interval() { start = 0; end = 0; }
        public Interval(int s, int e) { start = s; end = e; }
    }
    
    public class IntervalStartComparer : IComparer<Interval> {
       public int Compare(Interval x, Interval y) {
           return x.start.CompareTo(y.start);
       }
    }
    
    public class Solution {
        public bool CanAttendMeetings(Interval[] intervals) {
            Array.Sort(intervals, new IntervalStartComparer());
            for (int i = 0; i < intervals.Length - 1; i++)
            {
                Interval currInterval = intervals[i];
                Interval nextInterval = intervals[i + 1];
                if (currInterval.end > nextInterval.start) return false;
            }
            return true;
        }
    }
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.