harrytothemoon / leetcodeAplus

Leetcode meeting note
2 stars 0 forks source link

[56] Merge Intervals #42

Open windate3411 opened 4 years ago

windate3411 commented 4 years ago

一口氣一次過的感覺真~爽

var merge = function(intervals) {
    intervals.sort((a,b) => a[0] - b[0])
    let result = [intervals[0]]
    for (let i = 1; i < intervals.length; i++) {
        const currentInterval = intervals[i]
        const lastInterval = result[result.length - 1]
        if (currentInterval[0] <= lastInterval[1]) {
            lastInterval[1] = Math.max(lastInterval[1],currentInterval[1])
        } else {
            result.push(currentInterval)
        }
    }
    return result
};
tsungtingdu commented 4 years ago

A+ 題

var merge = function(intervals) {

    if (intervals.length < 2) return intervals

    intervals.sort((a,b) => {
      if(a[0] === b[0]) {
        return a[1] - b[1]
      } else {
        return a[0] - b[0]
      }
    })

    let ans = []
    let start = intervals[0][0]
    let end = intervals[0][1]

    for (let i = 0; i < intervals.length; i++) {
      if (intervals[i][0] > end) {
        ans.push([start, end])
        start = intervals[i][0]
      }

      if (intervals[i][1] > end) {
        end = intervals[i][1]
      }
    }
    ans.push([start, end])
    return ans
};
harrytothemoon commented 4 years ago
var merge = function(intervals) {
    if (intervals.length < 2) return intervals
    intervals.sort((a,b) => a[0] - b[0])
    let res = []
    let start = intervals[0][0]
    let end = intervals[0][1]
    let i = 1
    while(i < intervals.length) {
        if (intervals[i][0] > end) {
            res.push ([start, end])
            start = intervals[i][0]
        }
        if (intervals[i][1] > end) end = intervals[i][1]
        i++
    }
    res.push([start, end])
    return res
};