sisterAn / JavaScript-Algorithms

基础理论+JS框架应用+实践,从0到1构建整个前端算法体系
5.51k stars 634 forks source link

字节&leetcode56:合并区间 #99

Open sisterAn opened 4 years ago

sisterAn commented 4 years ago

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

示例 1:

输入: intervals = [[1,3],[2,6],[8,10],[15,18]]
输出: [[1,6],[8,10],[15,18]]
解释: 区间 [1,3] 和 [2,6] 重叠, 将它们合并为 [1,6].

示例 2:

输入: intervals = [[1,4],[4,5]]
输出: [[1,5]]
解释: 区间 [1,4] 和 [4,5] 可被视为重叠区间。

提示:

leetcode地址

sisterAn commented 4 years ago

待更新

jasonting5 commented 4 years ago
let merge = (intervals) => {
  const len = intervals.length;
  if (len === 0) return [];
  // 排序
  intervals.sort((s1, s2) => {
    return s1[0] - s2[0];
  })
  let arr = [];
  arr.push(intervals[0]);
  for (let i = 1; i < len; i++) {
    const arrLen = arr.length;
    if (intervals[i][0] < arr[arrLen - 1][1]) {
      arr[arrLen - 1][1] = intervals[i][1] > arr[arrLen - 1][1] ? intervals[i][1] : arr[arrLen - 1][1];
    } else {
      arr.push(intervals[i]);
    }
  }
  return arr
}
Cxy56 commented 4 years ago
function merge(arr) {
  arr.sort((a, b) => a[0] - b [0])
  for(let i = 0 ; i < arr.length - 1; i++) {
    let a2 = arr[i][1]
    let b1 = arr[i+1][0]
    let b2 = arr[i+1][1]
    if(a2 >= b1) {
      arr[i][1] = a2 >= b2 ? a2 : b2
      arr.splice(i+1, 1)
      i--
    }
  }
  console.log('arr', arr)
  return arr
}
let arr = [[1,3],[2,6],[8,10],[15,18]]
merge(arr)``
RabbDream commented 4 years ago
var merge = function(intervals) {
// 判断空数组
  if(intervals.length===0)  return []
// 以数组第一位升序排序
  intervals.sort((a,b)=>a[0]-b[0])
  let j = 1
// 初始化结果数组
  let res =  [intervals[0]]
  while(j<intervals.length){
// 如果遍历数组和结果数组最后一位无交集,直接放到结果集中
   if(intervals[j][0]>res[res.length-1][1]){
      res.push(intervals[j])
// 有交集时,更新结果集最后一位的最大值
    }else{
      res[res.length-1][1] = Math.max(res[res.length-1][1],intervals[j][1])
    }
    j++
  }
  return res
};
marlboroKay commented 4 years ago
var merge = function(intervals) {
  let res = []
  let len = intervals.length;
  if(len === 0) return res;
  intervals.sort((a, b) => a[0] - b[0]);
  for(let i = 0; i < len; i++){
    let curr = intervals[i]
    if(res.length && res[res.length-1][1] >= curr[0]){
      res[res.length-1][1] = Math.max(res[res.length-1][1], curr[1])
    }else{
      res.push(curr)
    }
  }
  return res
};