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
'Leetcode' 카테고리의 다른 글
[LeetCode] Reverse String 파이썬 (in-place, list.reverse()) (0) | 2021.04.12 |
---|---|
[LeetCode] Word Pattern 파이썬 (isomorphic, contract mapping) (0) | 2021.04.12 |
[LeetCode] Missing Number 파이썬 (0) | 2021.04.12 |
[LeetCode] Ugly Number 파이썬 (0) | 2021.04.11 |
[LeetCode] Add Digits 파이썬 (0) | 2021.04.11 |
댓글