mirror of
https://github.com/autistic-symposium/master-algorithms-py.git
synced 2025-06-05 13:49:08 -04:00
add some array playing
This commit is contained in:
parent
5732cfcc61
commit
5c55b81641
7 changed files with 263 additions and 0 deletions
arrays_and_strings
33
arrays_and_strings/array-duplicate-zeros.py
Normal file
33
arrays_and_strings/array-duplicate-zeros.py
Normal file
|
@ -0,0 +1,33 @@
|
|||
# Given a fixed-length integer array arr, duplicate each occurrence of zero,
|
||||
# shifting the remaining elements to the right.
|
||||
|
||||
|
||||
def duplicate_zeros(arr: list[int]) -> list[int]:
|
||||
"""
|
||||
Do not return anything, modify arr in-place instead.
|
||||
"""
|
||||
|
||||
i = 0
|
||||
while i < len(arr):
|
||||
|
||||
if arr[i] == 0 and i != len(arr) - 1:
|
||||
|
||||
range_here = len(arr) - (i + 2)
|
||||
while range_here > 0:
|
||||
arr[i + range_here + 1] = arr[i + range_here]
|
||||
range_here -= 1
|
||||
|
||||
arr[i+1] = 0
|
||||
i += 2
|
||||
|
||||
else:
|
||||
i += 1
|
||||
|
||||
|
||||
return arr
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
|
||||
arr = [1, 0, 2, 3, 0, 4, 5, 0]
|
||||
print(duplicate_zeros(arr))
|
Loading…
Add table
Add a link
Reference in a new issue