zlx362211854 / daily-study

每日一个知识点总结,以issue的形式体现
10 stars 6 forks source link

96. 算法题 #152

Open nanslee opened 4 years ago

nanslee commented 4 years ago

给出一个区间的集合,请合并所有重叠的区间。

输入: [[1,3],[2,6],[8,10],[15,18]]
输出: [[1,6],[8,10],[15,18]]
解释: 区间 [1,3] 和 [2,6] 重叠, 将它们合并为 [1,6].
输入: [[1,4],[4,5]]
输出: [[1,5]]
解释: 区间 [1,4] 和 [4,5] 可被视为重叠区间。
nanslee commented 4 years ago
/**
 * @param {number[][]} intervals
 * @return {number[][]}
 */
var merge = function(intervals) {
    let results = [];
    let len = intervals.length;
    if(len === 0) return [];

    intervals.sort((a, b) => a[0] - b[0]);

    let i = 0;
    while(i < len) {
      let currLeft = intervals[i][0];
      let currRight = intervals[i][1];
      while(i < len - 1 && currRight >= intervals[i + 1][0]) {
        i ++;
        currRight = Math.max(intervals[i][1], currRight)
      }
      results.push([currLeft, currRight]);
      i++;
    }

    return results;
};
goldEli commented 4 years ago
var merge = function(intervals) {
  const arr = []
  let now = intervals.shift()
  let prev
  while (now) {
    if (!prev) {
      prev = now
      continue
    }

    if (prev[1] >= now[0]) {
      prev = [
          prev[0] <= now[0] ? prev[0] : now[0], 
          prev[1] >= now[1] ? prev[1] : now[1] 
      ]
    } else {
      arr.push(prev)
      prev = now
    }

    now = intervals.shift()
    if (!now) {
      arr.push(prev)
    }
  }
  return arr    
};
zlx362211854 commented 4 years ago
var merge = (lists) => {
  var res = {}
  lists.reduce((a, b) => {
    if (b[0] >= a[0] && b[0] <= a[1]) {
      var concat = a.concat(b)
      var c = [Math.min(...concat), Math.max(...concat)]
      res[c] = c
      if (res[a]) {
        delete res[a]
      }
      return c
    } else {
      res[b] = b
      return b
    }
  })
  return Object.keys(res).map(i => res[i])
}
merge([[1, 3], [2, 6], [6, 7], [8, 10], [9, 18]])