Swift solution - Sort


  • 0
    class Solution {
        func merge(_ intervals: [Interval]) -> [Interval] {
            let n = intervals.count
            var starts = [Int](repeatElement(0, count: n))
            var ends = [Int](repeatElement(0, count: n))
            var result = [Interval]()
            var j = 0
            
            for i in 0..<n {
                starts[i] = intervals[i].start
                ends[i] = intervals[i].end
            }
            starts = starts.sorted()
            ends = ends.sorted()
            for i in 0..<n {
                if i == n - 1 || starts[i + 1] > ends[i] {
                    result.append(Interval(starts[j], ends[i]))
                    j = i + 1
                }
            }
            
            return result
        }
    }
    

Log in to reply
 

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