|
| 1 | +""" |
| 2 | +search_insert([1, 3, 5, 6], 3) => 1 |
| 3 | +search_insert([1, 3, 5, 6], 4) => 2 |
| 4 | +search_insert([1, 3, 5, 6], 7) => 4 |
| 5 | +search_insert([1, 3, 5, 6], 0) => 0 |
| 6 | +""" |
| 7 | + |
| 8 | +from typing import Any |
| 9 | + |
| 10 | + |
| 11 | +def bubble_sort(array: list) -> list: |
| 12 | + array = array.copy() |
| 13 | + length = len(array) |
| 14 | + for i in range(length - 1): |
| 15 | + swapped = False |
| 16 | + for j in range(length - i-1): |
| 17 | + if array[j] > array[j+1]: |
| 18 | + swapped = True |
| 19 | + array[j], array[j+1] = array[j+1], array[j] |
| 20 | + if not swapped: |
| 21 | + break |
| 22 | + return array |
| 23 | + |
| 24 | + |
| 25 | +def get_index(array: list, element: Any) -> int: |
| 26 | + index = 0 |
| 27 | + for item in array: |
| 28 | + if item == element: |
| 29 | + return index |
| 30 | + index += 1 |
| 31 | + return None |
| 32 | + |
| 33 | + |
| 34 | +def get_insert_place(array: list, target: int) -> int: |
| 35 | + low = 0 |
| 36 | + hight = len(array) - 1 |
| 37 | + while low <= hight: |
| 38 | + middle = (low + hight) // 2 |
| 39 | + if array[middle] < target: |
| 40 | + low = middle + 1 |
| 41 | + else: |
| 42 | + hight = middle - 1 |
| 43 | + return low |
| 44 | + |
| 45 | + |
| 46 | +def search_insert(array: list, number: int) -> int: |
| 47 | + # complexity: O(n^2) |
| 48 | + bubble_sort(array) |
| 49 | + # complexity: O(n) |
| 50 | + index = get_index(array, number) |
| 51 | + if index is None: |
| 52 | + # complexity: O(log n) |
| 53 | + return get_insert_place(array, number) |
| 54 | + return index |
| 55 | + |
| 56 | + |
| 57 | +if __name__ == "__main__": |
| 58 | + print(search_insert([1, 3, 5, 6], 3) == 1) |
| 59 | + print(search_insert([1, 3, 5, 6], 4) == 2) |
| 60 | + print(search_insert([1, 3, 5, 6], 7) == 4) |
| 61 | + print(search_insert([1, 3, 5, 6], 0) == 0) |
0 commit comments