[leetcode] 283. Move Zeroes

섬섬's 개발일지·2022년 1월 25일
0

leetcode

목록 보기
10/23

283. Move Zeroes

Problem

Given an integer array nums, move all 0's to the end of it while maintaining the relative order of the non-zero elements.

Note that you must do this in-place without making a copy of the array.

Example 1:

Input : nums = [0,1,0,3,12]
Output : [1,3,12,0,0]

Example 2:

Input : nums = [0]
Output : [0]

Constraints:

  • 1<= nums.length <= 10^4
  • -2^31 <= nums[i] <= 2^31 - 1

코드

class Solution(object):
    def moveZeroes(self, nums):
        """
        :type nums: List[int]
        :rtype: None Do not return anything, modify nums in-place instead.
        """
        non_zero = 0 # 0의 개수
        index = 0 # 0이 아닌 숫자를 넣어줄 index
        for num in nums :
            if num != 0 :
                nums[index] = num
                index += 1
                non_zero += 1
        nums[non_zero:] = [0] * (len(nums)-non_zero)
        
profile
섬나라 개발자

0개의 댓글