|
| 1 | +/** |
| 2 | + * Question Link: https://leetcode.com/problems/employee-free-time/ |
| 3 | + * Primary idea: Combine and merge sorted arrays. Then iterate through it to get offset between every two elements. |
| 4 | + * Time Complexity: O(n), Space Complexity: O(n) |
| 5 | + * |
| 6 | + * Definition for an Interval. |
| 7 | + * public class Interval { |
| 8 | + * public var start: Int |
| 9 | + * public var end: Int |
| 10 | + * public init(_ start: Int, _ end: Int) { |
| 11 | + * self.start = start |
| 12 | + * self.end = end |
| 13 | + * } |
| 14 | + * } |
| 15 | + */ |
| 16 | + |
| 17 | +class EmployeeFreeTime { |
| 18 | + func employeeFreeTime(_ schedule: [[Interval]]) -> [Interval] { |
| 19 | + let intervals = mergeIntervals(combineIntervals(schedule)) |
| 20 | + var res = [Interval]() |
| 21 | + |
| 22 | + for i in 1..<intervals.count { |
| 23 | + res.append(Interval(intervals[i - 1].end, intervals[i].start)) |
| 24 | + } |
| 25 | + |
| 26 | + return res |
| 27 | + } |
| 28 | + |
| 29 | + private func mergeIntervals(_ intervals: [Interval]) -> [Interval] { |
| 30 | + var res = [Interval]() |
| 31 | + |
| 32 | + for interval in intervals { |
| 33 | + if let last = res.last, last.end >= interval.start { |
| 34 | + res.removeLast() |
| 35 | + res.append(Interval(last.start, max(last.end, interval.end))) |
| 36 | + } else { |
| 37 | + res.append(interval) |
| 38 | + } |
| 39 | + } |
| 40 | + |
| 41 | + return res |
| 42 | + } |
| 43 | + |
| 44 | + private func combineIntervals(_ schedule: [[Interval]]) -> [Interval] { |
| 45 | + var res = schedule[0] |
| 46 | + |
| 47 | + for i in 1..<schedule.count { |
| 48 | + res = combineTwoIntervals(res, schedule[i]) |
| 49 | + } |
| 50 | + |
| 51 | + return res |
| 52 | + } |
| 53 | + |
| 54 | + private func combineTwoIntervals(_ l: [Interval], _ r: [Interval]) -> [Interval] { |
| 55 | + var res = [Interval](), i = 0, j = 0 |
| 56 | + |
| 57 | + while i < l.count || j < r.count { |
| 58 | + if i == l.count { |
| 59 | + res.append(r[j]) |
| 60 | + j += 1 |
| 61 | + } else if j == r.count { |
| 62 | + res.append(l[i]) |
| 63 | + i += 1 |
| 64 | + } else { |
| 65 | + if l[i].start <= r[j].start { |
| 66 | + res.append(l[i]) |
| 67 | + i += 1 |
| 68 | + } else { |
| 69 | + res.append(r[j]) |
| 70 | + j += 1 |
| 71 | + } |
| 72 | + } |
| 73 | + } |
| 74 | + |
| 75 | + return res |
| 76 | + } |
| 77 | +} |
0 commit comments