|
| 1 | +from bisect import bisect_left |
| 2 | +from typing import List |
| 3 | +from unittest import TestCase, main |
| 4 | + |
| 5 | + |
| 6 | +class Solution: |
| 7 | + def insert(self, intervals: List[List[int]], newInterval: List[int]) -> List[List[int]]: |
| 8 | + return self.solve(intervals, newInterval) |
| 9 | + |
| 10 | + """ |
| 11 | + Runtime: 1 ms (Beats 95.76%) |
| 12 | + Time Complexity: O(n) |
| 13 | + > intervals의 전체를 선형적으로 조회하므로 O(n), 그 외의 append등의 연산들은 O(1)이므로 무시 |
| 14 | + |
| 15 | + Memory: 18.70 MB (Beats 99.60%) |
| 16 | + Space Complexity: O(n) |
| 17 | + > result의 크기는 intervals와 newInterval이 하나도 겹치지 않는 경우, 최대 n + 1이므로, O(n + 1) ~= O(n) |
| 18 | + """ |
| 19 | + def solve(self, intervals: List[List[int]], newInterval: List[int]) -> List[List[int]]: |
| 20 | + if not intervals: |
| 21 | + return [newInterval] |
| 22 | + |
| 23 | + result = [] |
| 24 | + new_s, new_e = newInterval |
| 25 | + for interval in intervals: |
| 26 | + s, e = interval |
| 27 | + if e < new_s: |
| 28 | + result.append(interval) |
| 29 | + elif new_e < s: |
| 30 | + if new_s != -1 and new_e != -1: |
| 31 | + result.append([new_s, new_e]) |
| 32 | + new_s = new_e = -1 |
| 33 | + |
| 34 | + result.append(interval) |
| 35 | + else: |
| 36 | + new_s = min(new_s, s) |
| 37 | + new_e = max(new_e, e) |
| 38 | + |
| 39 | + if new_s != -1 and new_e != -1: |
| 40 | + result.append([new_s, new_e]) |
| 41 | + |
| 42 | + return result |
| 43 | + |
| 44 | + |
| 45 | +class _LeetCodeTestCases(TestCase): |
| 46 | + def test_1(self): |
| 47 | + intervals = [[1,2],[3,5],[6,7],[8,10],[12,16]] |
| 48 | + newInterval = [4,8] |
| 49 | + output = [[1,2],[3,10],[12,16]] |
| 50 | + self.assertEqual(Solution().insert(intervals, newInterval), output) |
| 51 | + |
| 52 | + def test_2(self): |
| 53 | + intervals = [[1,2]] |
| 54 | + newInterval = [3,4] |
| 55 | + output = [[1,2], [3,4]] |
| 56 | + self.assertEqual(Solution().insert(intervals, newInterval), output) |
| 57 | + |
| 58 | + def test_3(self): |
| 59 | + intervals = [[1,3], [5,6]] |
| 60 | + newInterval = [4,5] |
| 61 | + output = [[1,3], [4,6]] |
| 62 | + self.assertEqual(Solution().insert(intervals, newInterval), output) |
| 63 | + |
| 64 | + |
| 65 | +if __name__ == '__main__': |
| 66 | + main() |
0 commit comments