알고리즘/배열(array)

Move Zeroes python

자코린이 2023. 7. 5. 01:46

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

 

Follow up: Could you minimize the total number of operations done?

class Solution:
    def moveZeroes(self, nums: List[int]) -> None:
        """
        Do not return anything, modify nums in-place instead.
        
        1 <= nums.length <= 104
        -231 <= nums[i] <= 231 - 1

        input = [0,1,0,3,12]
        output = [1,3,12,0,0]
        """
        result = [0 for _ in range(len(nums))]
        j = 0
        if 0 not in nums:
            nums = nums[0:]
            if len(nums) == 1:
                nums[0] = nums[0]
            
        else:
            for i in range(len(nums)):
                if nums[i] != 0:
                    result[j] = nums[i]
                    j += 1
        
        for x in range(len(nums)):
            nums[x] = result[x]

class Solution:
    def moveZeroes(self, nums: list) -> None:
        slow = 0
        for fast in range(len(nums)):
            if nums[fast] != 0 and nums[slow] == 0:
                nums[slow], nums[fast] = nums[fast], nums[slow]

            if nums[slow] != 0:
                slow += 1

이 코드가 더 좋은 성능과 속도를 보여줍니다.

투포인터를 사용하여 푼 해답입니다.(역시 능력자는 많다는 것을 다시 배웁니다.)