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

插入区间 #59

Open
louzhedong opened this issue Sep 13, 2018 · 0 comments
Open

插入区间 #59

louzhedong opened this issue Sep 13, 2018 · 0 comments

Comments

@louzhedong
Copy link
Owner

习题

出处:LeetCode 算法第57题

给出一个*无重叠的 ,*按照区间起始端点排序的区间列表。

在列表中插入一个新的区间,你需要确保列表中的区间仍然有序且不重叠(如果有必要的话,可以合并区间)。

示例 1:

输入: intervals = [[1,3],[6,9]], newInterval = [2,5]
输出: [[1,5],[6,9]]

示例 2:

输入: intervals = [[1,2],[3,5],[6,7],[8,10],[12,16]], newInterval = [4,8]
输出: [[1,2],[3,10],[12,16]]
解释: 这是因为新的区间 [4,8] 与 [3,5],[6,7],[8,10] 重叠。

思路

顺序遍历,合并可以合并的项

解答

/**
 * Definition for an interval.
 * function Interval(start, end) {
 *     this.start = start;
 *     this.end = end;
 * }
 */
/**
 * @param {Interval[]} intervals
 * @param {Interval} newInterval
 * @return {Interval[]}
 */
var insert = function(intervals, newInterval) {
  var result = [];
  var start = newInterval.start;
  var end = newInterval.end;
  
  for (var i = 0; i< intervals.length;i  ) {
      if(intervals[i].end < start) {
          result.push(new Interval(intervals[i].start, intervals[i].end));
      } else if(intervals[i].start > end) {
          result.push(new Interval(intervals[i].start, intervals[i].end));
      } else {
          start = Math.min(start, intervals[i].start);
          end = Math.max(end, intervals[i].end);
          
      }
  }
  result.push(new Interval(start, end));
  result.sort(function(a, b) {return a.start - b.start});
  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