In-Place Swift Solution


  • 0
    Z
    class Solution {
        func merge(intervals: [Interval]) -> [Interval] {
            var sintervals = intervals.sort {
                if $0.start == $1.start
                {
                    return $0.end < $1.end
                }
                return $0.start < $1.start
            }
            var idx : Int = 0
            while (idx < sintervals.count)
            {
                if ((idx+1 < sintervals.count) && (sintervals[idx+1].start <= sintervals[idx].end))
                {
                    if (sintervals[idx+1].end > sintervals[idx].end)
                    {
                        sintervals[idx].end = sintervals[idx+1].end
                    }
                    sintervals.removeAtIndex(sintervals.startIndex.advancedBy(idx+1))
                }
                else
                {
                    idx++
                }
            }
            return sintervals
        }
    }

  • 0
    Z

    oops - not in-place... I changed that at the last moment.... :(


Log in to reply
 

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