|
| 1 | +""" |
| 2 | +last_occurrence([2, 2, 2, 3, 3, 4, 4, 5, 5, 5], 3) => 4 |
| 3 | +last_occurrence([2, 2, 2, 3, 3, 4, 4, 5, 5, 5], 2) => 2 |
| 4 | +complexity: O(log n) |
| 5 | +""" |
| 6 | + |
| 7 | +from typing import Any |
| 8 | + |
| 9 | + |
| 10 | +def last_occurrence(array: list, target: Any) -> int: |
| 11 | + low, high = 0, len(array) - 1 |
| 12 | + while low <= high: |
| 13 | + middle = (low + high) // 2 |
| 14 | + if target < array[middle]: |
| 15 | + high = middle - 1 |
| 16 | + else: # when array[middle] <= target |
| 17 | + low = middle + 1 |
| 18 | + if array[high] == target: |
| 19 | + return high |
| 20 | + return None |
| 21 | + |
| 22 | + |
| 23 | +if __name__ == "__main__": |
| 24 | + print(last_occurrence([2, 2, 2, 3, 3, 4, 4, 5, 5, 5], 3) == 4) |
| 25 | + print(last_occurrence([2, 2, 2, 3, 3, 4, 4, 5, 5, 5], 2) == 2) |
| 26 | + print(last_occurrence([2, 2, 2, 3, 3, 4, 4, 5, 5, 5], 4) == 6) |
| 27 | + print(last_occurrence([2, 2, 2, 3, 3, 4, 4, 5, 5, 5], 5) == 9) |
0 commit comments