A C# In-Place Solution but got Run Error


  • 0
    L

    Error because of parm "IList<Interval> intervals" was initialized as a fixed array but not a List<Interval>, so this solution works only when you pass the parm value properly.

    public IList<Interval> Insert(IList<Interval> intervals, Interval newInterval) {
        int curIndex = 0;
        for (int i = 0; i < intervals.Count; i++)
            if (intervals[i].start <= newInterval.start && intervals[i].end >= newInterval.start)
            {
                if (intervals[i].end < newInterval.end) intervals[i].end = newInterval.end;
                curIndex = i;
                break;
            }
            else if (i > 0 && newInterval.start < intervals[i].end && newInterval.start > intervals[i - 1].start)
            {
                intervals.Insert(i, newInterval);
                curIndex = i;
                break;
            }
            else if (i == 0 && newInterval.start < intervals[i].start)
            {
                intervals.Insert(0, newInterval);
                curIndex = 0;
                break;
            }
            else if (i == intervals.Count - 1 && newInterval.start > intervals[i].end)
            {
                intervals.Add(newInterval);
                curIndex = intervals.Count - 1;
                break;
            }
        for (int i = curIndex + 1; i < intervals.Count;)
        {
            if (intervals[i].end < intervals[curIndex].end) intervals.RemoveAt(i);
            else if (intervals[i].start > intervals[curIndex].end) break;
            else if (intervals[i].start <= intervals[curIndex].end && intervals[i].end >= intervals[curIndex].end)
            {
                intervals[curIndex].end = intervals[i].end;
                intervals.RemoveAt(i);
                break;
            }
        }
        return intervals;
    }

  • 0

    Seems like it complains about this line - Line 34: System.NotSupportedException: Collection is of a fixed size:

    intervals.Add(newInterval);

  • 0
    L

    Got it. I mocked up the same exception in local too. Thanks.


Log in to reply
 

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