[LeetCode 75] Move Zeros

HL·2023년 9월 4일

LeetCode 75

목록 보기
2/3

Q:

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.

Constraints:

  • 1 <= nums.length <= 104

A:

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

        '''
        move 0 to the end: delete 0, and append 0
        need to remember original index number (of pointer)
        end if checked original array's end position
        '''
        point_idx = 0
        # check numbers for original num's length times
        for _ in range(len(nums)):
            if nums[point_idx] == 0:
                # move 0 to the end
                del nums[point_idx]
                nums.append(0)
                # update point_idx
                pass
            else:
                # update point_idx
                point_idx += 1

Result:

Solved✅

More:

  • 다른 사람 솔루션: swap 이용
    class Solution:
        def moveZeroes(self, nums: List[int]) -> None:
            anchor = 0
            for explorer in range(len(nums)):
                if nums[explorer] != 0:
                    nums[anchor], nums[explorer] = nums[explorer], nums[anchor]
                    anchor += 1
  • 투포인터 좀 헷갈린다. 더 풀어봐야 할듯

0개의 댓글