My Swift solution


  • 0
    C

    func merge(intervals: [Interval]) -> [Interval] {

         if intervals.count <= 1 {
            return intervals
        }
        var myintervals = intervals
        var index = 0
        var j = 1
        while index < myintervals.count - 1 {
            j = index + 1
            while j < myintervals.count {
                if !(myintervals[index].end < myintervals[j].start || myintervals[index].start > myintervals[j].end) {
                    let start = min(myintervals[index].start, myintervals[j].start)
                    let end = max(myintervals[index].end, myintervals[j].end)
                    let node = Interval(start, end)
                    myintervals.removeAtIndex(index)
                    myintervals.removeAtIndex(j-1)
                    myintervals.insert(node, atIndex: 0)
                    index = 0
                    j = index + 1 // 有点回溯法的感觉,添加完之后,应该回头重新开始比较
                } else {
                    j += 1
                }
            }
            index += 1
        }
        return my intervals
    

    }


Log in to reply
 

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