57. Insert Interval
https://leetcode.com/problems/insert-interval/
js
/**
* 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) {
intervals.push(newInterval)
intervals.sort((a, b) => a.start - b.start)
var result = []
for (let interval of intervals) {
if (result.length === 0 || result[result.length - 1].end < interval.start) {
result.push(interval)
} else {
result[result.length - 1].end = Math.max(result[result.length - 1].end, interval.end)
}
}
return result
}
py
# Definition for an interval.
# class Interval(object):
# def __init__(self, s=0, e=0):
# self.start = s
# self.end = e
class Solution(object):
def insert(self, intervals, newInterval):
"""
:type intervals: List[Interval]
:type newInterval: Interval
:rtype: List[Interval]
"""
intervals.append(newInterval)
intervals.sort(key=lambda x: x.start)
result = []
for interval in intervals:
if not result or result[-1].end < interval.start:
result.append(interval)
else:
result[-1].end = max(result[-1].end, interval.end)
return result