//GitHub https://github.com/vellimole0621
LeetCode - Duplicate Zeros
문제 설명
:
Given a fixed-length integer array arr, duplicate each occurrence of zero, shifting the remaining elements to the right.
=> 고정된 길이의 수로 이루어진 배열 arr이 주어질 때, 요소 0이 있을 경우 0을 하나 복제한뒤. 나머지 요소들은 각각 그 다음 인덱스로 이동한다.
내 풀이
:
요소가 0이고 다음 요소와 그 다음 요소가 존재하는 경우, 다음 요소를 0으로 바꾸고 그 다음 요소부터는 이동한다. > 그 다음 요소를 검사할 때는 요소가 0인 경우, 이전 요소가 0이여서 0으로 바뀐 경우도 있으므로 중간 변수를 이용해 구분한다.
# Duplicate Zeros
# https://leetcode.com/explore/learn/card/fun-with-arrays/525/inserting-items-into-an-array/3245/
class Solution:
def duplicateZeros(self, arr: List[int]) -> None:
"""
Do not return anything, modify arr in-place instead.
"""
pass_num = 1
for i in range(0,len(arr)):
if arr[i] == 0 and pass_num == 1 and (i + 1) != len(arr):
if (i + 2) != len(arr):
for j in range(len(arr) - 2, i, -1):
arr[j + 1] = arr[j]
arr[i + 1] = 0
pass_num = -1
else:
arr[i + 1] = 0
elif pass_num == -1:
pass_num = 1
'프로그래밍 > Python' 카테고리의 다른 글
[파이썬 Python/알고리즘] LeetCode - Remove Element (0) | 2023.09.07 |
---|---|
[파이썬 Python/알고리즘] LeetCode - Merge Sorted Array (0) | 2023.09.05 |
[파이썬 Python/알고리즘] LeetCode - Squares of a Sorted Array (0) | 2023.09.05 |
[파이썬 Python/알고리즘] LeetCode - Find Numbers with Even Number of Digits (0) | 2023.08.29 |
[파이썬 Python/알고리즘] LeetCode - Max Consecutive Ones (0) | 2023.08.28 |