C#: Easy to Understand Solution with Explanation. (Accepted)


  • 1

    0_1521607321254_8c66fb3a-c827-4284-927b-1d105fdeebe6-image.png

    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 Solution {
        public int MinMeetingRooms(Interval[] intervals) {
            if (null == intervals) return 0;
            if (intervals.Length <= 1) return intervals.Length;
    
            int[] startTimes = new int[intervals.Length];
            int[] endTimes = new int[intervals.Length];
            for (int i = 0; i < intervals.Length; i++)
            {
                Interval curr = intervals[i];
                startTimes[i] = curr.start;
                endTimes[i] = curr.end;
            }
            Array.Sort(startTimes);
            Array.Sort(endTimes);
    
            int minMeetingRooms = 0; 
            int endTimesIterator = 0;
            for (int i = 0; i < startTimes.Length; i++)
            {
                minMeetingRooms++;       //Increment the room for the current meeting that is starting.
                //Check if startTime of current meeting is after endTime of meeting that is suppose to end first.
                if (startTimes[i] >= endTimes[endTimesIterator])
                {
                    minMeetingRooms--;   //since one meeting ended, a room got empty.
                    endTimesIterator++;  //move to the next endTime.
                }
            }
            return minMeetingRooms;
        }
    }
    

  • 0
    A

    This might fail if the input is not in sorted order


  • 0

    @arun.nagari1985 why? I am already taking care of input being not in sorted order by sorting startTimes and endTimes array that I am forming. Also, this solution passes all the tests that run when you submit it. May be I am missing something. Can you please explain it to me?


Log in to reply
 

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