|
| 1 | +/** |
| 2 | + * Question Link: https://leetcode.com/problems/insert-interval/ |
| 3 | + * Primary idea: First, check if nuewInterval's start is larger than one interval's end. |
| 4 | + * If so, save the index, otherwise save intervals |
| 5 | + * Second, keep updating a new interval if nuewInterval's end is larger then one interval's start |
| 6 | + * If cannot find more, append the new interval to the result array |
| 7 | + * Final Step, append the rest intervals to the result array |
| 8 | + * |
| 9 | + * Time Complexity: O(n), Space Complexity: O(1), |
| 10 | + * |
| 11 | + * Definition for an interval. |
| 12 | + * public class Interval { |
| 13 | + * public var start: Int |
| 14 | + * public var end: Int |
| 15 | + * public init(_ start: Int, _ end: Int) { |
| 16 | + * self.start = start |
| 17 | + * self.end = end |
| 18 | + * } |
| 19 | + * } |
| 20 | + */ |
| 21 | + |
| 22 | +class InsertInterval { |
| 23 | + func insert(_ intervals: [Interval], _ newInterval: Interval) -> [Interval] { |
| 24 | + var index = 0 |
| 25 | + var result: [Interval] = [] |
| 26 | + var tempInterval = Interval(newInterval.start, newInterval.end) |
| 27 | + |
| 28 | + while index < intervals.count && newInterval.start > intervals[index].end { |
| 29 | + result.append(intervals[index]) |
| 30 | + index += 1 |
| 31 | + } |
| 32 | + |
| 33 | + while index < intervals.count && newInterval.end >= intervals[index].start { |
| 34 | + let minStart = min(tempInterval.start, intervals[index].start) |
| 35 | + let maxEnd = max(tempInterval.end, intervals[index].end) |
| 36 | + tempInterval = Interval(minStart, maxEnd) |
| 37 | + index += 1 |
| 38 | + } |
| 39 | + result.append(tempInterval) |
| 40 | + |
| 41 | + for i in index ..< intervals.count { |
| 42 | + result.append(intervals[i]) |
| 43 | + } |
| 44 | + |
| 45 | + return result |
| 46 | + } |
| 47 | +} |
0 commit comments