Simple swift solution, O(nlogn) time with O(n) space


  • 0
    S

    Sort the intervals by start value than iterate through them and merge adjacent if they overlap.

    class Solution {
        func merge(_ intervals: [Interval]) -> [Interval] {
            
            var sorted = intervals.sorted { $0.start < $1.start }
            var merged = [Interval]()
            merged.reserveCapacity(intervals.count)
            
            for i in 0..<sorted.count {
                if i < sorted.count - 1 && sorted[i].end >= sorted[i+1].start {
                    sorted[i+1].start = min(sorted[i+1].start, sorted[i].start)
                    sorted[i+1].end = max(sorted[i+1].end, sorted[i].end)
                } else {
                    merged.append(sorted[i])
                }
                
            }
            
            return merged
        }
    }
    

Log in to reply
 

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