|
2 | 2 |
|
3 | 3 | from test_framework import generic_test
|
4 | 4 |
|
| 5 | +""" |
| 6 | +ex: k=17, [1, -11, 2, -2, -19, 4, -9, 1, 10, -12, 6, -19, 9, -5, 0, 5, -4, 13, 19, 19, 11] |
| 7 | +return [-19, -19, -12, -11, -9, -5, -4, -2, 0, 1, 1, 2, 4, 5, 6, 9, 10, 11, 13, 19, 19] |
| 8 | +
|
| 9 | +- brute force is just sorting the array |
| 10 | +- if k is 0, array is already sorted |
| 11 | +- if k is 1, then between arr[i-1], arr[i], and arr[i+1] there is a minimal element. |
| 12 | +- the smallest element of the array is within k of 0. |
| 13 | +- the second smallest element is within k of 1. |
| 14 | +- if k is greater than or equal to array len, no better than brute force |
| 15 | +
|
| 16 | +""" |
| 17 | +from heapq import heappush, heappop |
| 18 | + |
5 | 19 |
|
6 | 20 | def sort_approximately_sorted_array(sequence: Iterator[int],
|
7 | 21 | k: int) -> List[int]:
|
8 |
| - # TODO - you fill in here. |
9 |
| - return [] |
| 22 | + heap = [] |
| 23 | + ans = [] |
| 24 | + i = 0 |
| 25 | + while i <= k: |
| 26 | + try: |
| 27 | + heappush(heap, next(sequence)) |
| 28 | + except StopIteration: |
| 29 | + pass |
| 30 | + i += 1 |
| 31 | + while heap: |
| 32 | + ans.append(heappop(heap)) |
| 33 | + try: |
| 34 | + heappush(heap, next(sequence)) |
| 35 | + except StopIteration: |
| 36 | + continue |
| 37 | + return ans |
10 | 38 |
|
11 | 39 |
|
12 | 40 | def sort_approximately_sorted_array_wrapper(sequence, k):
|
13 | 41 | return sort_approximately_sorted_array(iter(sequence), k)
|
14 | 42 |
|
15 | 43 |
|
16 | 44 | if __name__ == '__main__':
|
| 45 | + cases = [ |
| 46 | + ([1, -11, 2, -2, -19, 4, -9, 1, 10, -12, 6, -19, 9, -5, 0, 5, -4, 13, 19, 19, 11], 17), |
| 47 | + ([1, 2, 3, 4, 5, 6, 7], 0), |
| 48 | + ([2, 1, 4, 3, 7, 6, 9, 8], 1), |
| 49 | + ] |
| 50 | + for case, k in cases: |
| 51 | + expected = sorted(case) |
| 52 | + actual = sort_approximately_sorted_array_wrapper(case, k) |
| 53 | + assert actual == expected, f"\n{k}:{case}\n{actual} != {expected}" |
17 | 54 | exit(
|
18 | 55 | generic_test.generic_test_main(
|
19 | 56 | 'sort_almost_sorted_array.py', 'sort_almost_sorted_array.tsv',
|
|
0 commit comments