Nailer's blog

Leetcode move zeros(Python)

January 3rd, 2020


๋ฌธ์ œ ๋งํฌ

์ ‘๊ทผ (์˜์‹์˜ ํ๋ฆ„)

์•„๋ž˜ ๋‘ ์กฐ๊ฑด์ด ์‹ ๊ฒฝ์“ฐ์˜€์ง€๋งŒ ๊ทธ๋ƒฅ filter ํ•จ์ˆ˜๋ฅผ ์‚ฌ์šฉํ•˜๊ณ  ๊ธฐ์กด ๊ธธ์ด์—์„œ ๋ถ€์กฑํ•œ ๋งŒํผ 0์œผ๋กœ ์ฑ„์šฐ๋Š” ๋ฐฉ๋ฒ•์„ ์‚ฌ์šฉํ•˜๋ ค ํ–ˆ์–ด์š”. ํ•˜์ง€๋งŒ ์—ญ์‹œ filter๋Š” ์ƒˆ๋กœ์šด array๋ฅผ ๋งŒ๋“ค์–ด์ฃผ๊ธฐ ๋•Œ๋ฌธ์— ๋ฌธ์ œ ์กฐ๊ฑด์„ ๋งŒ์กฑ์‹œํ‚ค์ง€ ๋ชปํ–ˆ์–ด์š”.

๋ฌธ์ œ์กฐ๊ฑด

1. You must do this in-place without making a copy of the array.
2. Minimize the total number of operations.

๊ฒฐ๊ตญ ์™„์ „ ํƒ์ƒ‰์„ ํ•˜๋ฉฐ 0์ธ ๊ฒฝ์šฐ ์‚ญ์ œํ•˜๊ณ , ๋ช‡ ๊ฐœ ์‚ญ์ œํ–ˆ๋Š”์ง€ ๊ธฐ์–ตํ•ด๋‘๊ณ  ๋‚˜์ค‘์— ๋’ค์— ๋ถ™์—ฌ์ฃผ๋Š” ๋ฐฉ์‹์œผ๋กœ ๋ฌธ์ œ๋ฅผ ํ’€์—ˆ์–ด์š”.

์ฝ”๋“œ

class Solution:
    def moveZeroes(self, nums: List[int]) -> None:
        idx = 0
        zerocounter = 0
        while idx < len(nums):
            if nums[idx] == 0:
                del nums[idx]
                zerocounter += 1
                continue
            idx += 1
        nums += [0]*zerocounter

image-20200103114028190

๋ฌด๋‚œํ•˜์ง€๋งŒ ์„ฑ๋Šฅ ํ–ฅ์ƒ์— ๋Œ€ํ•ด์„œ ์ข€ ๋” ๊ณต๋ถ€๊ฐ€ ํ•„์š”ํ•œ ๊ฒƒ ๊ฐ™์•„์š”.

Created by SeongHeum CHOI, 2020