본문 바로가기
Leetcode

[LeetCode] Move Zeros 파이썬 (in-place)

by YGSEO 2021. 4. 12.
728x90

in-place modifiy

class Solution(object):
    def moveZeroes(self, nums):
        """
        :type nums: List[int]
        :rtype: void Do not return anything, modify nums in-place instead.
        """
        pos = 0
        for i in range(len(nums)):
            if nums[i]:
                nums[i], nums[pos] = nums[pos], nums[i]
                pos += 1

 

 

nums[i]가 0이 아닌경우 0의 위치와 swap한다.

# i track non zero location
# pos track zero location

# print(nums[i], nums[pos] , "i={}, pos={}".format(i,pos))
# print(nums)
# 1 0 i=1, pos=0
# [1, 0, 0, 3, 12]
# 3 0 i=3, pos=1
# [1, 3, 0, 0, 12]
# 12 0 i=4, pos=2
# [1, 3, 12, 0, 0]

 

 

 

 

 

출처: github.com/jiapengwen/LeetCode/blob/master/Python/move-zeroes.py

728x90

댓글