283. Move Zeroes

Numeric_combo·2024년 11월 21일

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 <= 104
-231 <= nums[i] <= 231 - 1

투포인터를 쓰는 건데, 이전에 했던 것처럼 left, right = 0, len(input)-1 같은 게 아니라 left만 0으로 initialize해서 풀어야한다. 않이 투포인터가 이렇게도 쓸 수도 있는 거구나...정형화 시키지 말자. 투포인터란 말 그대로 어떤 테크닉이지 그것의 implementation 코드 또한 정형화된 게 아니란 걸 잊지 말자.

class Solution:
    def moveZeroes(self, nums: List[int]) -> None:
        """
        Do not return anything, modify nums in-place instead.
        """
        left = 0

        for right in range(len(nums)):
            if nums[right] != 0:
                nums[right], nums[left] = nums[left], nums[right]
                left += 1
        
        return nums
profile
덕질기록용

0개의 댓글