Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

合并乱序区间 #258

Open
wuxianqiang opened this issue Mar 29, 2020 · 0 comments
Open

合并乱序区间 #258

wuxianqiang opened this issue Mar 29, 2020 · 0 comments

Comments

@wuxianqiang
Copy link
Owner

题目来源:今日头条面试题

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

let arr = [[1,3],[2,6],[8,10],[15,18]]
// [ [ 1, 6 ], [ 8, 10 ], [ 15, 18 ] ]

结果

function merge(intervals) {
  if (!intervals || !intervals.length) return [];
  intervals.sort((a, b) => a[0] - b[0]); // 按照区间第一位进行排序
  let result = [intervals[0]] // 排序之后第一个是最小的
  // [[1,3]]
  for (let i = 1; i < intervals.length; i++) { // 从第二个开始比较
    let resultLast = result.length - 1
    if (result[resultLast][1] > intervals[i][0]) { // 判断结尾是不是大于开始
      result[resultLast][1] = Math.max(result[resultLast][1], intervals[i][1]) // 区间重复就进行合并了
    } else {
      result.push(intervals[i]) // 区间没有重复
    }
  }
  return result
}

console.log(merge(arr))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant