[LeetCode] 283. Move Zeroes

Semidragon·2023년 8월 12일
0

CodingTest

목록 보기
9/80

1. Question

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]

2. Thoughts

For ex) [0,1,0,3,12]

  1. route all non-zeros to the front
    => [1,3,12]
  2. fill remaining with zeros
    => [1,3,12,0,0]

3. Tips learned

4. My solution

class Solution:
    def moveZeroes(self, nums: List[int]) -> None:
        count = 0
        for i in range(len(nums)):
            if nums[i] != 0:
                nums[count] = nums[i]
                count += 1
        nums[count:] = [0] * (len(nums) - count)
Accepted
75/75 cases passed (59 ms)
Your runtime beats 96.58 % of python3 submissions
Your memory usage beats 16.32 % of python3 submissions (16.5 MB)

5. AI Solution and Improvements

Your code is correct and already quite efficient. It moves non-zero elements to the front of the array and fills the remaining positions with zeros. Since you're interested in making it more Pythonic or looking for improvements, you could simplify the loop logic using the enumerate function:

class Solution:
    def moveZeroes(self, nums: List[int]) -> None:
        count = 0
        for i, num in enumerate(nums):
            if num != 0:
                nums[count], nums[i] = nums[i], nums[count]
                count += 1

The enumerate function makes it easier to iterate over both the index i and the value num simultaneously. This approach continues to follow the in-place constraint and maintains linear time complexity.

profile
Semidragon's network [CS undergrad @ Sungkyunkwan University | Networks + System @ CSI]

0개의 댓글