Summary
배열에서 0을 발견하면 중복 삽입하고 이후 요소들은 오른쪽으로 밀어낸다.
요소의 이동이 핵심인 문제입니다.
example
Input: arr = [1,0,2,3,0,4,5,0]
Output: [1,0,0,2,3,0,0,4]
Explanation: After calling your function, the input array is modified to: [1,0,0,2,3,0,0,4]
Constraints
1 <= arr.length <= 104
0 <= arr[i] <= 9
possible_dups = 0
length_ = len(arr) - 1
for left in range(length_ + 1):
if left > length_ - possible_dups:
break
if arr[left] == 0:
if left == length_ - possible_dups:
arr[length_] = 0
length_ -= 1
break
else:
possible_dups += 1
if left > length_ - possible_dups:
if arr[left] == 0:
if left == length_ - possible_dups:
arr[length_] = 0 와 length_ -= 1
배열에서 0을 발견하면 이를 중복삽입한다.
last = length_ - possible_dups
# Copy zero twice, and non zero once.
for i in range(last, -1, -1):
if arr[i] == 0:
arr[i + possible_dups] = 0
possible_dups -= 1
arr[i + possible_dups] = 0
else:
arr[i + possible_dups] = arr[i]
for i in range(last, -1, -1):
if arr[i] == 0:
arr[i + possible_dups] = 0
possible_dups -= 1
arr[i + possible_dups] = 0
else:
arr[i + possible_dups] = arr[i]
Time Complexity
Space Complexity
초보자용 코드
from typing import List
class Solution:
def duplicateZeros(self, arr: List[int]) -> None:
new_arr = [] # 새로운 리스트를 만들어서 0을 중복 삽입할 공간 확보
for num in arr: # 배열의 요소를 하나씩 확인
new_arr.append(num) # 원래 숫자 추가
if num == 0: # 만약 0이면 한 번 더 추가
new_arr.append(0)
# 배열 크기를 초과하지 않도록 제한
if len(new_arr) >= len(arr):
break
# 원래 배열에 복사 (in-place로 유지)
for i in range(len(arr)):
arr[i] = new_arr[i]
left > length_ - possible_dups 조건이 이를 보장한다.possible_dups(중복할 0 개수)와 last(마지막 가능한 위치) 같은 변수를 미리 계산해야 한다.