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

合并区间 #23

Open
louzhedong opened this issue May 11, 2018 · 0 comments
Open

合并区间 #23

louzhedong opened this issue May 11, 2018 · 0 comments

Comments

@louzhedong
Copy link
Owner

louzhedong commented May 11, 2018

题目

出处:LeetCode 算法第56题

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

示例 1:

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

示例 2:

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

思路

对所有项按start大小进行排序,遍历所有的项。

解答

/**
 * Definition for an interval.
 * function Interval(start, end) {
 *     this.start = start;
 *     this.end = end;
 * }
 */
/**
 * @param {Interval[]} intervals
 * @return {Interval[]}
 */
var merge = function (intervals) {
  if (intervals.length <= 1) {
    return intervals;
  }
  var result = [];
  intervals.sort(function (a, b) {
    return a.start - b.start;
  });

  var start = intervals[0].start;
  var end = intervals[0].end;
  for (var i = 0; i < intervals.length; i++) {
    if (intervals[i].start <= end) {
      end = Math.max(end, intervals[i].end);
    } else {
      result.push(new Interval(start, end));
      start = intervals[i].start;
      end = intervals[i].end;
    }
  }

  result.push(new Interval(start, end));
  return result;
};
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