C# solution


  • 0
    Q

    C# solution

    public class Solution {
        public IList<Interval> Merge(IList<Interval> intervals, bool isFirst = true) {
        var input = new List<Interval>(intervals);
        if(isFirst){
            input.Sort((a, b) => ((Interval)a).start >= ((Interval)b).start ? 1 : -1);
        }
        var n = input.Count;
        if (n <= 1) return input;
        for (int i = 0; i < n; i++){
            var cur = input[i];
            if(i == n-1) {
            break;
            }
            var next = input[i + 1];
            if (next.start > cur.end) continue;
            else {
                var mergedNode = new Interval(cur.start, Math.Max(next.end,cur.end));
                input[i] = null;
                input[i+1] = mergedNode;
            }
        }
        
        var result = new List<Interval>();
        foreach(var item in input){
            if(item != null) result.Add(item);
        }
        return result;
        }
    }
    

Log in to reply
 

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