283. Move Zeroes

개굴·2024년 5월 22일

leetcode

목록 보기
7/51
  • python3

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

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

Pseudocode

My solution

  1. Set two pointers: one for tracking non-zero elements and one for the current element.
  2. Increment the current pointer.
  3. Swap elements when the non-zero pointer's element is not zero.

Other solution

  1. Move non-zero elements to the front.
  2. Fill the remaining positions with zeros.

Code

My solution

class Solution:
    def moveZeroes(self, nums: List[int]) -> None:
        """
        Do not return anything, modify nums in-place instead.
        """
        readingPointer = 0;
        
        for nonZeroPointer in range(0, len(nums)):
            if nums[nonZeroPointer] != 0 and nums[readingPointer] == 0:
                temp = nums[nonZeroPointer]
                nums[nonZeroPointer] = nums[readingPointer]
                nums[readingPointer] = temp
                readingPointer+=1
            if nums[readingPointer] !=0:
                readingPointer+=1

Other solution

class Solution:
    def moveZeroes(self, nums: List[int]) -> None:
        """
        Do not return anything, modify nums in-place instead.
        """
        nonZeroPointer = 0
        
        # 첫 번째 단계: 0이 아닌 요소를 앞으로 이동
        for i in range(len(nums)):
            if nums[i] != 0:
                nums[nonZeroPointer] = nums[i]
                nonZeroPointer += 1
        
        # 두 번째 단계: 남은 부분을 0으로 채우기
        for i in range(nonZeroPointer, len(nums)):
            nums[i] = 0

Result

Both solutions have same results

Time Complexity : O(n) as we are traveling the array only once.
Space Complexity : O(1) as we are not using any extra space.

Review

  • I solved this problem on my own. Honestly, it is the first time since I started solving problems on LeetCode. I'm proud of myself.
profile
알쏭달쏭혀요

0개의 댓글