🔍 문제
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.
Input: nums = [0,1,0,3,12]
Output: [1,3,12,0,0]
Input: nums = [0]
Output: [0]
🖥 실행
1) Answer
class Solution:
def moveZeroes(self, nums: List[int]) -> None:
n = 0
while nums.count(0) > n:
nums.remove(0)
nums.append(0)
n += 1
2) Better Solution
class Solution(object):
def moveZeroes(self, nums):
i = 0
for j in range(len(nums)):
if nums[j] != 0:
nums[i], nums[j] = nums[j], nums[i]
i += 1
'Coding test > LeetCode' 카테고리의 다른 글
[LeetCode] Max Consecutive Ones II (0) | 2022.05.20 |
---|---|
[LeetCode] Height Checker (0) | 2022.05.20 |
[LeetCode] Replace Elements with Greatest Element on Right Side (0) | 2022.05.20 |
[LeetCode] Valid Mountain Array (0) | 2022.05.20 |
[LeetCode] Merge Sorted Array (0) | 2022.05.20 |